代码随想录算法训练营第一天|数组理论基础,Leetcode 704. 二分查找,27. 移除元素

Leetcode 704. 二分查找 Binary Search - LeetCode

 二分区间:左闭右闭,左闭右开

左闭右闭:合法区间,left和right相等的时候是不是合法【1,1】

left = 0; 

right = nums.length - 1;

while (left <= right)

        mid = left + (right - left) / 2;

        if (nums[mid] > target) //左闭右闭, nums[mid]一定不是搜索的值

                right = mid - 1;

        else if (nums[mid] < target) //更新右区间的左边界

                left = mid + 1;

        else

                return mid;

return -1;

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

左闭右开:[left, right) [1, 1)不合法

left = 0;

right = nums.length

while (left < right)

        mid = left + (right - left) / 2;

         if (nums[mid] > target) //【1, 1),不包含右边

                right = mid;

          else if (nums[mid] < target)//[1, 1), nums[mid]已经< target了

                left = mid + 1;

        else return mid

return -1;

class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length;

        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > target) {
                right = mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}

 27. 移除元素         Remove Element - LeetCode     

1 2 3 4 5

1 2 4 5 5

双指针:

fast:寻找新数组里所需要的元素

slow:需要更新的下标

slow = 0;

for (fast = 0; fast < nums.size(); fast++){

        if (nums[fast] != val){

                nums[slow] = nums[fast]//把fast指向的值赋给slow指针的位置

                        slow++;

        }

}

return slow;

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

你可能感兴趣的:(代码随想录算法训练营,算法,leetcode,职场和发展)