Article directory
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.
- If arr[start] is even and arr[end] is odd, swap two elements, start++,end–.
- 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.
- If arr[start] is an odd number, start++ until start points to an even number.
- 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,7
to take3,8
.
After reading the title, it is very similar leetcode
to 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
, starting0
with - Set a large index
right
, startingarray.length
from - Judging whether
array[left] + array[right]
the values
meets the conditions - Eligible - Back
- greater than
sum
,right
move left - less than
sum
,left
move 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 S
and print out all sequences of consecutive positive numbers whose sum is S.
For example : input 15
, ordered === 1+2+3+4+5
so print out 3 consecutive sequences , and .4+5+6
7+8
15
1-5
5-6
7-8
ideas
- Creates a container
child
to represent the current subsequence with initial elements of1,2
small
Record the beginning and end elements of a subsequencebig
big
Move the end of the subsequence to thesmall
right to number- When the sum of the subsequences is greater than the target value,
small
move to the right, and when the sum of the subsequences is less than the target value,big
move 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;
}