fix45 from CodingBat

Problem:

(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]

My solution:

public int[] fix45(int[] nums) {
  // two lists store indices of unpaired 4s and 5s
  List<Integer> indicesOf4 = new ArrayList<>();
  List<Integer> indicesOf5 = new ArrayList<>();
  
  for(int i = 0; i < nums.length; i++) {
    if(nums[i] == 4 && nums[i+1] != 5)
      indicesOf4.add(i);
    if(i == 0 && nums[i] == 5 || i != 0 && nums[i] == 5 && nums[i-1] != 4)
      indicesOf5.add(i);
  }
  
  int cnt = 0;
  for(Integer i: indicesOf4) {
    nums[indicesOf5.get(cnt++)] = nums[i+1];
    nums[i+1] = 5;
  }
  return nums;
}


An excellent solution:

public int[] fix45(int[] nums) {
  int[] otherValues = new int[nums.length];

  for(int i = 0, c = 0; i < nums.length; i++)
    if(nums[i] != 4 && nums[i] != 5)
      otherValues[c++] = nums[i];

  for(int i = 0, c = 0; i < nums.length; i++)
    if(nums[i] == 4)
      nums[++i] = 5;
    else
      nums[i] = otherValues[c++];

  return nums;
}

from irrelephant on java - Is there a simpler solution for Codingbat fix45? - Stack Overflow 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值