代码随想录算法训练营第一天| 704. Binary Search、27. Remove Element

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:

  1. If we are using both sides open interval [low, high], it would allow while(low <= high),because it fits the rule. And when it encounters nums[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;
  1. If we are using Left-Closed And Right-Open interval, it could only allow while(low < high).And when nums[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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值