Day 1 | 704. Binary Search | 27. Remove Element | 35. Search Insert Position | 34. First and Last Po


Basics of Array Theory

  • Array index start from 0
  • Array is a data collection stored in the contiguous memory space
  • Because the array’s memory space is contiguous, we must modify the other element address when deleting or adding elements
  • We can’t delete array elements, only overwritten

LeetCode 704. Binary Search

Question Link

Solution:

class Solution {
	// avoid looping when tartget less than nums[0] and bigger than nums[nums.length - 1]
    if(target < nums[0] || target > nums[nums.length-1])
    	return -1;
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        // left-closed and right-closed interval
        while(left <= right) {
            int middle = (left + right) >> 1;
            if(nums[middle] > target)
                right = middle - 1;
            else if(nums[middle] < target)
                left = middle + 1;
            else    
                return middle;
        }
        return -1;
    }
}

Thoughts:

  • Avoid looping when target less than nums[0] and bigger than nums[nums.length - 1]
  • Two greater than signs >> means move one place to the right. >> 1 means divide by 2.
  • Two less than signs << means move one place to the left. << 1 means multiple 2.
  • The prerequisite of using binary search is an ordered distinct array.
  • We have to follow the loop invariant principle. It means we should do our boundary operation according to the interval’s definition.
  • We define target in a left-closed and right-closed interval,that is[left, right].
  • We use left <= right in the while loop. Because left == right makes sense.

LeetCode 27. Remove Element

Question Link

Solution:

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];
                slow++;
            }
        }
        return slow;
    }
}

Time Complexity: O(n)
Space Complexity: O(1)

Thoughts:

  • I adopt the Two Pointers Method. Complete the work of 2 for loop under 1 for loop through a slow and a fast point.
  • The principle of solving this two-pointer question is clarifying the definition of these two pointers.
  • Fast Point: find elements of the new array that doesn’t contain the target val.
  • Slow Point: update new array index.

LeetCode 35. Search Insert Position

Question Link

Solution:

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

Time Complexity:O(log n)
Space Complexity:O(1)

Thoughts:

  • If the question says Given a sorted array of distinct integers, we can consider whether we could use Binary Search.
  • Accoring to loop invariant principle. We define target in a left-closed and right-closed interval, that is [left, right]
  • Insert the target value to the array,there are four situations:
    • 1、target value comes before all elements of the array: [0, -1]
    • 2、target value is equal to an element in the array: return middle
    • 3、target value is in the array: [left, right],return right + 1
    • 4、target value is behind all elements:[left, right]:return right + 1;
      在这里插入图片描述
    • When left exceeds right, the loop ends. At this time, left points to the position of the first element larger than target, while right points to the position of the last element smaller than target

LeetCode 34. First and Last Position of Element in Sorted Array

Question Link

Solution:

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int rightBorder = getRightBorder(nums, target);
        int leftBorder = getLeftBorder(nums, target);
        // Situation one: `target` in the left or right of the array
        if (rightBorder == -2 || leftBorder == -2)
            return new int[]{-1,-1};
        // Situation three: `target` in the array's range, also in the array.
        if (rightBorder - leftBorder > 1)
            return new int[]{leftBorder + 1, rightBorder - 1};
        // Situation two: `target` in the array's range but not in the array. 
        return new int[]{-1, -1};
    }

    int getLeftBorder(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int leftBorder = -2;
        while(left <= right) {
            int middle = (left + right) >> 1;
            // update right when nums[middle] == target
            if (nums[middle] >= target) {
                right = middle - 1;
                leftBorder = right;
            } else {
                left = middle + 1;
            }            
        }
        return leftBorder;
    }
    
    int getRightBorder(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        int rightBorder = -2;
        while(left <= right) {
            int middle = (left + right) >> 1;
            if (nums[middle] > target) {
                right = middle -1;
            } 
            // update left when nums[middle] == target
            else {
                left = middle + 1;
                rightBorder = left;
            }            
        }
        return rightBorder;
    }
}

Thoughts:

  • There are three situations:
    • Situation one: target in the left or right of the array. Like an array {3, 4, 5}, the target is 2 or 6. Should return {-1, -1}
    • Situation two: target in the array’s range but not in the array. Like an array {3, 6, 7}, the target is 5. Should return {-1, -1}
    • Situation three: target in the array’s range, also in the array. Like an array {3, 6, 7}, the target is 6. Should return {1, 1}.
  • Because of left points to the position of the first element larger than target, while right points to the position of the last element smaller than target. Therefore there must be at least one element between them, which is target.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值