forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_977.java
38 lines (35 loc) · 1.07 KB
/
_977.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.fishercoder.solutions;
import java.util.Arrays;
public class _977 {
public static class Solution1 {
/**
* O(nlogn) solution
*/
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
result[i] = (int) Math.pow(nums[i], 2);
}
Arrays.sort(result);
return result;
}
}
public static class Solution2 {
/**
* O(n) solution
*/
public int[] sortedSquares(int[] nums) {
int[] ans = new int[nums.length];
for (int i = nums.length - 1, left = 0, right = nums.length - 1; i < nums.length && left <= right; i--) {
if (Math.abs(nums[left]) < Math.abs(nums[right])) {
ans[i] = nums[right] * nums[right];
right--;
} else {
ans[i] = nums[left] * nums[left];
left++;
}
}
return ans;
}
}
}