This is the third day of my participation in the August Text Challenge.More challenges in August

Mobile zero

The title

Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements.

Example: input: [0,1,0,3,12] output: [1,3,12,0,0]Copy the code

Answer key

Idea 1: Iterate through the number group and delete the number that is 0. Finally, fill in the missing position with 0.

Idea 2: Use the left and right Pointers to point to the left and right boundaries of 0. When the traversal encounters a value that is not 0, the value is exchanged with the 0 of the left boundary, and the left and right boundaries move backward. When a value of 0 is encountered, extend the bounded value of 0 directly and proceed to the next step.

code

Idea 1:

var moveZeroes = function (nums) {
    let len = nums.length - 1
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] == 0) {
            nums.splice(i, 1)
            i--
        }
    }
    while (nums.length <= len) {
        nums.push(0)}return nums
};
Copy the code

Idea 2:

var moveZeroes = function (nums) {
    let l = 0, r = 0, index = 0
    while (index < nums.length) {
        if (nums[index] == 0) {
            r = index++
        } else {
            swap(nums, l++, index++)
            r++
        }
    }
    return nums
};
function swap(arr, i, j) {
    let temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}
Copy the code

Sum of two numbers II – Enter an ordered array

The title

Given an array of integers in ascending order numbers, find two numbers that add up to the target number.

The function should return the subscript values of these two numbers as an array of integers of length 2. The subscript of numbers starts at 1, so the answer array should be 1 <= answer[0] < answer[1] <= numbers. Length.

You can assume that each input corresponds to a unique answer, and you can’t reuse the same elements.

Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 equals the target number 9. So index1 = 1, index2 = 2.Copy the code

Answer key

There must be a single pair of answers in the input array, so we can ignore the absence. Sequential arrays use left and right Pointers to head and tail. Judge the sum of the two cases: equal directly return; If the value is greater than the target value, it indicates that the tail value is too large. Reduce the range and move the right pointer to the left. If the value is smaller than the target value, the left pointer is too small and moves to the right. Until the left and right Pointers meet.

code

var twoSum = function (numbers, target) {
    let l = 0, r = numbers.length - 1, mid
    while (l < r) {
        if (numbers[l] + numbers[r] === target) return [l + 1, r + 1]
        if (numbers[l] + numbers[r] > target) r--
        else if (numbers[l] + numbers[r] < target) l++
    }
    return [-1, -1]};Copy the code

LeetCode