力扣T704二分查找 T27移出元素

代码随想录训练营第二期第一天 T704二分查找 T27移出元素
题目链接:
https://leetcode.cn/problems/binary-search/
https://leetcode.cn/problems/remove-element/

二分查找

二分法(左闭右闭 [0,nums.length-1])  常用左闭合右闭合这种二分法 而不是左闭右开
class Solution {
    public int search(int[] nums, int target) {
         int left=0;
         int right=nums.length-1;  //0到最后一个下标
        while(left<=right){  //判断条件
           int  mid=(right-left)/2+left;
            if(target==nums[mid])
              return mid;
            if(target<nums[mid]){
              right=mid-1;
            }else{
              left=mid+1;
            }
        }
        return -1;
    }
}

二分法(左闭右闭 [0,nums.length) )
class Solution {
    public int search(int[] nums, int target) {
        //左闭右开
         int left=0;
         int right=nums.length;//(0,nms.length)
        while(left<right){
           int  mid=(right-left)/2+left;
            if(target==nums[mid])
              return mid;
            if(target<nums[mid]){
              right=mid;
            }else{
              left=mid+1;
            }
        }
        return -1;
    }
}

移出元素(双指针 快慢指针 快指针往前移 做替换)

双指针 快慢指针
class Solution {
    public int removeElement(int[] nums, int val) {
        // 快慢指针
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != val) {
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }
        return slowIndex;
    }
}

你可能感兴趣的:(leetcode)