代码随想录一刷day01

#**

力扣704二分查找

**
##左闭右闭

class Solution {
    public int search(int[] nums, int target) {
        int low = 0, high = nums.length-1, mid;
        if(target < nums[0] || target > nums[nums.length-1]){
            return -1;
        }
        while(low <= high){
            mid = (low + high)>>1;
            if(target == nums[mid]){
                return mid;
            }else if(target > nums[mid]){
                low = mid + 1;
            }else{
                high = mid - 1;
            }
        }
        return -1;
    }
}

##左闭右开
左闭右开时,while的条件low < high 带不带等号,high的取值如何确定:数组内只有两个元素时一目了然
右闭左开也是同理

class Solution {
    public int search(int[] nums, int target) {
        int low = 0, high = nums.length, mid;
        while(low < high){
            mid = (low + high)>>1;
            if(target == nums[mid]){
                return mid;
            }else if(target > nums[mid]){
                low = mid + 1;
            }else{
                high = mid;
            }
        }
        return -1;
    }
}

#**

力扣27移除元素

**
#快慢指针法

class Solution {
    public int removeElement(int[] nums, int val) {
        int a = 0, b = 0;
        for(; a < nums.length; ){
            if(nums[a] == val){
                a++;
            }else{
                nums[b++] = nums[a++];
            }
        }
        return b;
    }
}

#双向指针法
有点类似归并排序的操作,不过不如快慢指针法便捷

你可能感兴趣的:(算法,leetcode,数据结构)