704. Binary Search
Method Since the Array provided is already sorted and unduplicated,the only task to do is narrowing down the interval to get the target
Core Idea The defination of Open/Closed Interval is crucial:
- If we are using both sides open interval [low, high], it would allow
while(low <= high)
,because it fits the rule. And when it encountersnums[mid] != target
, mid will no longer be in the interval, so that there will be
if(nums[mid] < target)
low = mid +1;
else if(nums[mid] > target)
high= mid -1;
- If we are using Left-Closed And Right-Open interval, it could only allow
while(low < high)
.And whennums[mid]!=target
, mid won’t be in the interval, but sinceRight-Open, mid will appear on the right but not included :
if(nums[mid] < target)
low = mid +1;
else if(nums[mid] > target) // not included since Right-Open
high= mid;
Difficulty Did not get clear with the difination of Interval, which makes the branches unreasonalble
27. Remove Element
Method Fast And Slow Pointers, the fast one move forward each loop, when it encount a number that does not equal to val, assign the value to index slow, and slow++, slow represents the length after remove repeated val
int removeElement(vector<int>& nums, int val) {
int slow = 0;
for(int fast = 0; fast < nums.size(); ++fast)
{
if(nums[fast] != val)
{
nums[slow++] = nums[fast];
}
}
return slow;
}
First Though Same as the method, but the second pointer is traversing backwards from the end
int removeElement_1(vector<int>& nums, int val) {
int len = nums.size(); // record the length of non-duplicated arr
for(int i = 0; i < len; ++i)
{
if(nums[i] == val)
{
while(len > 0 && nums[len - 1] == val) // moving backwards until len-1'val is not equal to target
{
--len;
}
if(i >= len)
{
return len;
}
nums[i] = nums[--len];
}
}
return len;
}