-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path977. Squares of a Sorted Array.java
63 lines (57 loc) · 1.34 KB
/
977. Squares of a Sorted Array.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int [] ans = new int [n];
int neg,pos;
neg=pos=Integer.MAX_VALUE;
if(nums[0]>=0)
{
pos = 0;
neg = -1;
}
else
{
for(int i=0;i<n;i++)
{
if(nums[i]>=0)
{
pos = i;
neg = i-1;
break;
}
}
}
if(neg==Integer.MAX_VALUE)
{
pos = n;
neg = n-1;
}
for(int k=0 ; pos<n || neg>=0;k++)
{
if(neg<0)
{
ans[k] = nums[pos]*nums[pos];
pos++;
continue;
}
if(pos>=n)
{
ans[k] = nums[neg]*nums[neg];
neg--;
continue;
}
if((nums[neg]*nums[neg])<(nums[pos]*nums[pos]))
{
ans[k] = nums[neg]*nums[neg];
//System.out.println(ans[k]+" "+k);
neg--;
}
else
{
ans[k] = nums[pos]*nums[pos];
pos++;
}
}
return ans;
}
}