-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove Element.cpp
89 lines (81 loc) · 1.87 KB
/
Remove Element.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int removeElement(vector<int>& nums, int val) {
sort(nums.begin(),nums.end());
int len=nums.size();
if (len==0)
return 0;
if (len==1)
{
if (nums[0]==val)
return 0;
else
return 1;
}
int high=len-1,low=0,mid=(high+low)/2;
while (low<high)
{
if (nums[mid]>val)
{
high=mid-1;
mid=(low+high)/2;
}
else if (nums[mid]<val)
{
low=mid+1;
mid=(high+low)/2;
}
else
{
break;
}
}
int p1=mid,p2=mid+1;
if (p2>len-1)
p2=len-1;
while (true)
{
if (p1>=0)
{
if (nums[p1]==val)
{
nums.erase(nums.begin()+p1);
if (p1-1>=0)
p1--;
if (p2-1>=0)
p2--;
len--;
if (len==0)
break;
}
}
if (p2<len)
{
if (nums[p2]==val)
{
cout<<0;
nums.erase(nums.begin()+p2);
len--;
if (len==0)
break;
if (p2>=len)
p2=len-1;
}
}
if (nums[p1]!=val&&nums[p2]!=val)
break;
}
return nums.size();
}
int main()
{
vector<int> num;
num.push_back(4);
num.push_back(5);
num.push_back(5);
int i=removeElement(num,5);
cout<<i;
return 0;
}