LeetCode # 977
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation:
After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Example 2:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Constraints:
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104
- nums is sorted in non-decreasing order.
Solution #1
class Solution {
public int[] sortedSquares(int[] nums) {
int[] s = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
s[i] = nums[i] * nums[i];
}
Arrays.sort(s);
return s;
}
}
Result #1
💡 간단하게 Arrays.sort()를 구현하여 문제를 풀었다. 하지만 Arrays.sort()의 시간 복잡도는 O(n log n).
Solution #2 (1ms)
class Solution {
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
int left = 0, right = nums.length-1;
for (int i = nums.length-1; i >=0; i--) {
if(Math.abs(nums[left])>Math.abs(nums[right])){
result[i] = nums[left] * nums[left];
left++;
}
else{
result[i] = nums[right] * nums[right];
right--;
}
}
return result;
}
}
Result #2
💡 left, right 인덱스를 증감시켜 절댓값 비교를 하는 방법으로 풀었다. 1ms로 시간이 감소한 결과를 볼 수 있다.
More Algorithm!
👇👇
github.com/ggujangi/ggu.leet-code
출처 : leetCode
'LeetCode > Easy' 카테고리의 다른 글
[Java] LeetCode 914 : X of a Kind in a Deck of Cards (0) | 2021.04.17 |
---|---|
[Java] LeetCode 1486 : XOR Operation in an Array (0) | 2021.04.17 |
[Java] LeetCode 1295 : Find Numbers with Even Number of Digits (0) | 2021.03.30 |
[Java] LeetCode 485 : Max Consecutive Ones (0) | 2021.03.30 |
[JAVA] LeetCode Explore - May Week 1 : First Bad Version (0) | 2020.05.03 |