[47] (Dual pointer) remove element | (binary search) search for insertion position (LC 27 | LC 35)

Remove element

Problem Description

Given an array of nums and a value of val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.

Don't use extra array space, you must only use O(1) extra space and modify the input array in-situ.

The order of the elements can be changed. You don't need to consider the elements in the array beyond the new length.

Problem-solving thoughts

This question is of the same type as yesterday's question ( deleting duplicates in the sorted array ), so you can still use double pointers to solve the problem, but note that the two pointers here start from position 0.

There are two more points to note, which have been marked in the code:

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        int n = nums.length;
        if(n == 0) return 0;
        int i = 0;
        for(int j=0;j<n;j++){
    
    
            if(nums[j] != val)
                nums[i++] = nums[j]; //注意:这里只能用i++,不能用++i;
        }
        return i;//返回的是i,不是i+1
    }
}

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

Search for insertion location

Problem Description

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, return the position where it will be inserted in order.

You can assume that there are no duplicate elements in the array.

Problem-solving thoughts

This is a simple question that can be traversed directly. The time complexity O(n) can be solved, but the test point is not this. So I think in the direction of binary search. The time complexity can be optimized to O(logn).

Code:

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

Time complexity: O(logn)
Space complexity: O(1)

Guess you like

Origin blog.csdn.net/qq_43424037/article/details/114589938