【CodingBat】 fix34 & fix45 问题

问题描述: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, ... ]组合不计入统计之中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值