-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathfix34.java
30 lines (24 loc) · 904 Bytes
/
fix34.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
/* Return an array that contains exactly the same numbers as the given array,
* but rearranged so that every 3 is immediately followed by a 4. Do not move
* the 3's, but every other number may move. The array contains the same
* number of 3's and 4's, every 3 has a number after it that is not a 3 or 4,
* and a 3 appears in the array before any 4.
*/
public int[] fix34(int[] nums) {
int i = 0;
while(i < nums.length && nums[i] != 3)
i++;
int j = i + 1;
while(j < nums.length && nums[j] != 4)
j++;
while(i < nums.length) {
if(nums[i] == 3) {
nums[j] = nums[i+1];
nums[i+1] = 4;
while(j < nums.length && nums[j] != 4)
j++;
}
i++;
}
return nums;
}