The first day of code random recording algorithm training camp | 704. Binary search, 27. JavaScript implementation of removing elements

 

Reference Articles and Videos

Theoretical Basics of Arrays: Random Thoughts on Code (programmercarl.com)

Topic 1: 704. Binary Search

topic description

 Given an ordered (ascending) integer array nums of n elements and a target value target, write a function to search for target in nums, and return the subscript if the target value exists, otherwise return -1. 704. Binary Search - LeetCode

first thought

We can traverse in the order of the array. If the target is found during the traversal process, its corresponding subscript can be returned. If the target value is not found after traversing the entire array, -1 will be returned.

! However, the array to be searched is ordered. We can compare the size of the target value with the current array element during the search process. If the target value is smaller than the current array element, then if there is a target value, its index must be smaller than the current element The index value of ; if the target value is greater than the current array element, then if there is a target value, its index must be greater than the index value of the current element. Therefore, the left and right pointers can be set to point to the minimum and maximum values ​​of the interval to be compared. When the two pointers meet, either the subscript corresponding to the target value is found, or -1 is returned if not found.

Need to pay attention to two special cases: the value to be found is smaller than the minimum value of the array; the value to be found is greater than the maximum value of the array.

Thoughts after reading the code random thoughts

while loop condition is `left<=right` or `left<right` and `right = mid -1` or `right = mid`?

It depends on whether the interval contains boundary values:

①[left,right]: In this case, right= mid-1 and left = mid+1 should be taken, and the loop condition should be left<=right. First of all, the current nums[mid] must not be the target, then the end subscript position of the left interval to be searched next is mid - 1. It is also because mid-1 may be equal to left, so the loop condition should be left<=right. For example, if you search for 5 in [5], if left<right, the final return result will be -1 instead of 0, which is obviously a wrong result.

②[left,right):  In this case, right= mid and left = mid should be taken, and the loop condition should be left<right. In the case of an open interval, it means that the right cannot be obtained, that is to say, the logic in our code is right=mid, nums[mid] has been compared with the target, and the next cycle does not need to consider this mid so The loop condition should be left<right. If target is not in the array, left and right will eventually be equal to mid, and left<=right will always be satisfied, and will not jump out of the loop.

var search = function(nums, target) {
    let left = 0;
    let right = nums.length-1;
    while (left <=  right) {
        let mid =parseInt((left + right)/2);
        if(target > nums[mid] ) {
            left = mid;
        }else if (target < nums[mid] ) {
            right = mid;
        } else if(target == nums[mid]) {
            return mid;
        }
    }
    return -1;
};

Difficulties Encountered in Implementation

can't break out of loop

In JavaScript, methods such as parseInt() should be used to convert the calculation method of `/` (divided by ÷) into an integer, otherwise the value of mid will be a decimal 2.

Topic 2: 27. Remove elements

topic description

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

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

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

Example 1: Given nums = [3,2,2,3], val = 3, the function should return the new length 2, and the first two elements in nums are both 2. You don't need to consider elements in the array beyond the new length.

Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2, the function should return the new length 5, and the first five elements in nums are 0, 1, 3, 0, 4.

first thought

For JavaScript, you can use the operation method of the Array object to directly traverse to find the value equal to val in the array and delete it.

var removeElement = function(nums, val) {
    let i =0;
    while(i<nums.length) {
        if(nums[i] == val) {
            nums.splice(i,1);
        } else {
            i = i+1;
        }
    }
    return  nums.length
};

Thoughts after reading the code random thoughts

Double pointer method -  using fast and slow pointers

Slow pointer: We need to update the subscript. So how to update it? We update it with fast pointers.

We make the fast pointer traverse the elements in the array normally, and the slow pointer traverses along with the fast pointer, nums[slow]=nums[fast]. When the fast pointer points to an element whose value is equal to val, the slow pointer does not move, and continues to update when the fast pointer points to the next element in the next cycle (until the fast pointer points to an element not equal to val, the element updated to the slow pointer will not be updated at this time. Including val), at this time nums[slow]=nums[fast+1], then the original value will be overwritten by the new element pointed to by the fast pointer.

var removeElement = function(nums, val) {
    let s =0;
    for(let k= 0; k < nums.length;k++) {
        if(nums[k] != val) {
            nums[s++] = nums[k];            
        }
    }
    return s
};

Difficulties Encountered in Implementation

1. It should be noted that the slice method will not change the original array, but create a new array. According to the meaning of the question, a new array cannot be created, so slice() cannot be used

2. After splice deletes elements, nums is a new array, and the following elements will be advanced. Therefore, after deleting the current element, you should continue to compare the array element pointed to by the current subscript with val.

3. s++: The return value of s++ is equivalent to s, nums[s++] = nums[k] is equivalent to nums[s] = nums[k]; s++;

4. The return length is s instead of s+1, the reason is the same as above, s has been added to the original basis.

learning gains

Binary search: For binary search, the definition of an interval is an invariant. In the process of binary search, the invariant must be maintained, that is, in the while search, each boundary processing must be operated according to the definition of the interval, which is the rule of loop invariance.

For the need to update the array linked list, you can consider using fast and slow pointers.

Guess you like

Origin blog.csdn.net/qq_42101569/article/details/126978731