sorted array consisted of squares of input integers

本文介绍了一种算法,该算法接收一个已排序的整数数组作为输入,并返回一个新的数组,其中包含输入数组中每个整数的平方,并按升序排列。通过双指针技术高效地实现了这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给你一个sorted Integer array,输出sorted array consisted of squares of input integers,比如[1,3,5] -> [1,9,25]

[-3, -1, 0, 1, 2] -> [0, 1, 1, 4, 9]

package array;

public class SortSquare {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] array = { -5, -3, 0, 1, 6 };
		int[] res = square1(array);
		for (int i : res) {
			System.out.println(i);
		}
	}

	public static int[] square1(int[] nums) {
		if (nums == null || nums.length == 0)
			return new int[0];
		int left = 0, right = nums.length - 1, index = right;
		int[] res = new int[nums.length];
		while (left <= right) {
			if (Math.abs(nums[left]) >= Math.abs(nums[right])) {
				res[index--] = nums[left] * nums[left];
				left++;
			} else {
				res[index--] = nums[right] * nums[right];
				right--;
			}
		}
		return res;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值