快捷搜索:  汽车  科技

leet code算法思想(LeetCode进阶977-双指针)

leet code算法思想(LeetCode进阶977-双指针)Example 2:Output: [0 1 9 16 100]Given an array of integers A sorted in non-decreasing order return an array of the squares of each number also in sorted non-decreasing order.Example 1:Input: [-4 -1 0 3 10]

leet code算法思想(LeetCode进阶977-双指针)(1)

概要

双指针是一种比较常见的算法思想,在循环遍历数组时经常会用到。双指针主要有两种算法技巧:1、快慢指针(例如已发推文中的LeetCode进阶-实战之快慢指针(阿里面试题)),利用指针确定的相对位置关系,快指针先到达边界的特点进行搜索;2、双向指针,双向指针的特点两指针分别从前往后和从后往前遍历,本文介绍的正是这种用法。

原题

977. Squares of a Sorted Array (Easy)

Given an array of integers A sorted in non-decreasing order return an array of the squares of each number also in sorted non-decreasing order.

Example 1:

Input: [-4 -1 0 3 10]

Output: [0 1 9 16 100]

Example 2:

Input: [-7 -3 2 3 11]

Output: [4 9 9 49 121]

Note:

1 <= A.length <= 10000

-10000 <= A[i] <= 10000

A is sorted in non-decreasing order.

977.有序数组的平方

给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

示例 1:

输入:[-4 -1 0 3 10]

输出:[0 1 9 16 100]

示例 2:

输入:[-7 -3 2 3 11]

输出:[4 9 9 49 121]

提示:

1 <= A.length <= 10000

-10000 <= A[i] <= 10000

A 已按非递减顺序排序。

  • 分类:双指针

分析&&思路

根据题意,数组为非递减顺序,数组中可能存在负数和非负数。负数在数组中从左到右平方(绝对值)依次变小,正数从右到左平方(绝对值)依次变小。因此采用双指针分别从左往右、从右往左对比交换。

伪代码

1、new一个大小与入参大小一致的int数组;

2、声明两个指针下标,从左往右的指针和从右往左的指针;

3、for循环,从数组尾下标到起始下标0

i.若从右往左正数绝对值较大则将较大绝对值的数平方放入数组末位,同时从右到左指针左移一位;

ii.若从左往右非正数绝对值较大则将较大绝对值的数放入数组末位,同时从左到右指针右移一位;

4、循环结束,返回新数组的平方数的有序数组;

编码实践

public int[] sortedSquares(int[] A) {

int n = A.length;

int[] result = new int[n];

int i = 0 j = n - 1;

for (int p = n - 1; p >= 0; p--) {

if (Math.abs(A[i]) > Math.abs(A[j])) {

result[p] = A[i] * A[i ];

} else {

result[p] = A[j] * A[j--];

}

}

return result;

}

结语

本篇介绍了双指针中比较经典的双向指针的用法,相对简单但是比较有代表性适合算法基础入门。事实上双向指针在很多经典的算法思想中都有出现,典型的比如快速排序就有用到。最后,如果觉得本篇对你有所帮助,不妨关注走一波~

leet code算法思想(LeetCode进阶977-双指针)(2)

关注订阅号 获取更多干货~

猜您喜欢: