-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRearrbysign_2149
52 lines (47 loc) · 1.18 KB
/
Rearrbysign_2149
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
Rearrange - Every consecutive pair of integers have opposite signs.
For all integers with the same sign, the order in which they were present in nums is preserved.
The rearranged array begins with a positive integer.
My code - -
class Solution {
public int[] rearrangeArray(int[] nums) {
int l = nums.length;
int [] arr = new int[l];
int k=0;
for(int i=0;i<l;i++){
if(nums[i]>0){
arr[k]=nums[i];
k=k+2;
}
}
k=1;
for(int i=0;i<l;i++){
if(nums[i]<0){
arr[k]=nums[i];
k=k+2;}
}
return arr;
}
}
Optimised version -
class Solution {
public int[] rearrangeArray(int[] nums) {
int n = nums.length;
int postIndex = 0;
int negaIndex = 1;
int[] ans = new int[n];
for (int i = 0; i < n; i++)
{
if (nums[i] < 0)
{
ans[negaIndex] = nums[i];
negaIndex += 2;
}
else
{
ans[postIndex] = nums[i];
postIndex += 2;
}
}
return ans;
}
}