代码随想录算法训练营 day 1: 704 binary search 27 Remove element

200 阅读1分钟
  1. Binary Search

Easy

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

需要注意左闭右开和左闭右闭的不同写法,即[left, right)和[left, right]的不同。

左闭右开代码实现:

class Solution {
    public int search(int[] nums, int target) {
        int left=0;
        int right = nums.length; //右端为数组MAX INDEX + 1

        while(left < right) {
            int mid = left + (right - left) / 2; // 降低溢出概率

            if(nums[mid] > target) {
                right = mid; //右端为mid而不能为mid - 1
                continue;
            }
            else if (nums[mid] < target)  {
                left = mid + 1; //左端封闭,满足此状态时,left不满足条件。
            }
            else {
                return mid;
            }
        }


        return -1;
    }
}
  1. Remove Element

Easy

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

移除元素可以暴力解,使用二层嵌套循环,每找到一个目标元素,都将后续元素全部前移一位,并将目标元素移动至数组末尾。TC: O(N ^ 2)

使用快慢指针可以O(N)解。初始化fast和slow两个index指向数组起始位置,检查fast指针位置是否等于目标值。若是,只移动fast,若否,则将slow位置元素与fast位置交换,并同时移动fast和slow。最后返回slow。

class Solution {
    public int removeElement(int[] nums, int val) {
        int slow = 0;
        int fast = 0;

        while(fast < nums.length) {
            if(nums[fast] == val) {
                fast++;
                continue;
            }
            else {
                int temp = nums[slow];
                nums[slow] = nums[fast];
                nums[fast] = temp;

                fast++;
                slow++;
            }
        }

        return slow;

    }
}