Data Structures and Algorithms (7) Array Series - Use of Double Pointers in Arrays

Array - double pointer

Arrays are the most common data structures we see in development, and are used to store collections of elements in order. But the elements can be accessed randomly, because each element in the array can be identified by the array index. When inserting and deleting, it is necessary to move subsequent elements, and the expansion problem must be considered, and the insertion is slow.

Arrays are closely related to daily business development. How to make good use of arrays is the key to whether we can develop high-quality code.

1 The use of double pointers in arrays

A class of problems mentioned in the above linked list mainly uses two or more pointers in different positions to solve the problem through the transformation of speed and direction. Note that this trick is often used in sorted arrays.

1.1 Adjust the order of the array so that the odd numbers come before the even numbers

topic

Take an array of integers and implement a function to reorder the numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array

ideas

Two pointers start and end, one starts from the front and the other starts from the back, compare the elements pointed to by the pointers.

  1. If arr[start] is even and arr[end] is odd, swap two elements, start++,end–.
  2. If arr[start] is an even number, arr[end] is also an even number, end–, until the end pointer points to an odd number, swap.
  3. If arr[start] is an odd number, start++ until start points to an even number.
  4. When the start>end exchange is complete.

code

function reOrderArray(arr) {
    
    
  let start = 0;
  let end = arr.length - 1;
  while (start < end) {
    
    
    //奇数
    while (arr[start] % 2 === 1) {
    
    
      start++;
    }
    //此时start所指为偶数,对后面判断
    while (arr[end] % 2 === 0) {
    
    
      end--;
    }
    //此时end所指为奇数,若start<end交换
    if (start < end) {
    
    
      // let temp = arr[start];
      // arr[start] = arr[end];
      // arr[end] = temp;
      // 使用解构赋值:
      [arr[start], arr[end]] = [arr[end], arr[start]]
    }
  }
  return arr;
}

If you need to keep the relative order unchanged, you cannot use the above writing method, you need to let the two pointers start from the left at the same time

1.2 and two numbers for S

topic

Input an increasing-sorted array and a number S, find two numbers in the array so that their sum is exactly S, if the sum of multiple pairs of numbers is equal S, output the smallest product of the two numbers.

ideas

There may be multiple pairs of qualified results in the array, and the one with the smallest output product is required, indicating that it should be distributed on both sides, such as 3,8 5,7to take 3,8.

After reading the title, it is very similar leetcodeto the first question [Sum of two numbers], but there is an obviously different condition in the title that the array is ordered, which can be solved by using the size pointer, constantly approximating the result, and finally obtaining the final value.

  • Set a small index left, starting 0with
  • Set a large index right, starting array.lengthfrom
  • Judging whether array[left] + array[right]the value smeets the conditions
  • Eligible - Back
  • greater than sum, rightmove left
  • less than sum, leftmove right
  • If left=right, no matching result

code

function FindNumbersWithSum(array, sum) {
    
    
  let left = 0;
  let right = array.length - 1;
  while (left < right) {
    
    
    const s = array[left] + array[right];
    if (s > sum) {
    
    
      right--;
    } else if (s < sum) {
    
    
      left++;
    } else {
    
    
      return [array[left], array[right]]
    }
  }
  return [];
}

1.3 A sequence of consecutive positive integers whose sum is S

topic

Enter a positive number Sand print out all sequences of consecutive positive numbers whose sum is S.

For example : input 15, ordered === 1+2+3+4+5so print out 3 consecutive sequences , and .4+5+67+8151-55-67-8

ideas

  • Creates a container childto represent the current subsequence with initial elements of1,2
  • smallRecord the beginning and end elements of a subsequencebig
  • bigMove the end of the subsequence to the smallright to number
  • When the sum of the subsequences is greater than the target value, smallmove to the right, and when the sum of the subsequences is less than the target value, bigmove to the right

code

function FindContinuousSequence(sum) {
    
    
    const result = [];
    const child = [1, 2];
    let big = 2;
    let small = 1;
    let currentSum = 3;
    while (big < sum) {
    
    
        //序列和小于目标值 且big小于目标值执行,直至超过目标值
        //存入数组,sum变化,big右移
        while (currentSum < sum && big < sum) {
    
    
            child.push(++big);
            currentSum += big;
        }
        //序列和大于目标值,且指针没越位,直至越位
        while (currentSum > sum && small < big) {
    
    
            //移除child的第一个元素
            child.shift();
            //左指针自增 sum变化。
            currentSum -= small++;
        }
        //如果值符合,且序列个数>1,存入结果数组,继续寻找。
        if (currentSum === sum && child.length > 1) {
    
    
            result.push(child.slice());
            child.push(++big);
            currentSum += big;
        }
    }
    return result;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324133734&siteId=291194637