问题描述:fix34问题
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, and a 3 appears in the array before any 4.
fix34([1, 3, 1, 4]) → [1, 3, 4, 1]
fix34([1, 3, 1, 4, 4, 3, 1]) → [1, 3, 4, 1, 1, 3, 4]
fix34([3, 2, 2, 4]) → [3, 4, 2, 2]
代码:
(a stupid method using 3 for-loops)
public int[] fix34(int[] nums) {
/*第一个for循环*/
int count = 0;
for(int i:nums) {
if(i==3) count++;
}
/*第二个for循环*/
int[] pos3 = new int[count];
int[] pos4 = new int[count];
int i3 = 0, i4 = 0;
for(int i=0;i<nums.length;i++) {
if(nums[i]==3) pos3[i3++] = i;
else if(nums[i]==4) pos4[i4++] = i;
}
/*第三个for循环*/
for(int i=0;i<count;i++) {
int a=pos3[i], b=pos4[i];
int temp = nums[a+1];
nums[a+1] = nums[b];
nums[b] = temp;
}
return nums;
}
思路:
第一个for循环:统计3出现的次数,记为count
第二个for循环:新建数组pos3存储所有3出现的位置,数组pos4存储所有4出现的位置
第三个for循环:把每一个4调换到对应的3的位置后面。
问题描述:fix45问题
(This is a slightly harder version of the fix34 problem.) Return an array that contains exactly the same numbers as the given array, but rearranged so that every 4 is immediately followed by a 5. Do not move the 4's, but every other number may move. The array contains the same number of 4's and 5's, and every 4 has a number after it that is not a 4. In this version, 5's may appear anywhere in the original array. fix45([5, 4, 9, 4, 9, 5]) → [9, 4, 5, 4, 5, 9] fix45([1, 4, 1, 5]) → [1, 4, 5, 1] fix45([1, 4, 1, 5, 5, 4, 1]) → [1, 4, 5, 1, 1, 4, 5] |
代码:(在fix34代码基础上进行一点改动)
public int[] fix45(int[] nums) {
int count = 0;
for(int i=0;i<nums.length;i++) {
if(nums[i]==4&&nums[i+1]!=5) count++;
}
int[] pos4 = new int[count];
int[] pos5 = new int[count];
int i4 = 0, i5 = 0;
for(int i=0;i<nums.length;i++) {
if(nums[i]==4&&nums[i+1]!=5) pos4[i4++] = i;
else if(nums[i]==5&&(i==0||nums[i-1]!=4)) pos5[i5++] = i;
}
for(int i=0;i<count;i++) {
int a=pos4[i], b=pos5[i];
int temp = nums[a+1];
nums[a+1] = nums[b];
nums[b] = temp;
}
return nums;
}
思路:与fix34不同之处在于,数组中原有的[ ..., 4, 5, ... ]组合不计入统计之中。