双指针法-有序数组的平方

1|0有序数组的平方

有序数组的平方

  1. 暴力法: 平方后排序
  2. 首尾指针: 1)首尾指针元素选取平方的最大值添加入新数组, 对应指针移动, 循环是while(left <= right)

2|0题解

//双指针法(首尾指针法):时间复杂度O(n),空间复杂度O(n) class Solution { public int[] sortedSquares(int[] nums) { int[] result = new int[nums.length]; int left = 0, right = nums.length - 1; int insertIndex = result.length - 1; while (left <= right) { if (nums[left] * nums[left] < nums[right] * nums[right]) { result[insertIndex] = nums[right] * nums[right]; right--; } else { result[insertIndex] = nums[left] * nums[left]; left++; } insertIndex--; } return result; } } // 直接法(暴力解法):对每个元素平方O(n) + 快速排序O(nlogn) class Solution2 { public int[] sortedSquares(int[] nums) { for (int i = 0; i < nums.length; i++) { nums[i] = nums[i] * nums[i]; } Arrays.sort(nums); return nums; } }

__EOF__

本文作者Rocky
本文链接https://www.cnblogs.com/nrocky/p/15887993.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   -Rocky-  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示