简体   繁体   English

使用数组和仅一个循环的偶数在奇数之前

[英]Even numbers before odd numbers using array and only one loop

I attempted the problem. 我尝试了这个问题。 I am not getting the right solution. 我没有找到正确的解决方案。 Kindly help. 请帮助。

Problem : Return an array that contains the exact same numbers as the given array, but rearranged so that all the even numbers come before all the odd numbers. 问题:返回一个数组,该数组包含与给定数组完全相同的数字,但重新排列后,所有偶数都在所有奇数之前。 Other than that, the numbers can be in any order. 除此之外,数字可以按任何顺序排列。 You may modify and return the given array, or make a new array. 您可以修改并返回给定的数组,或者创建一个新的数组。

 evenOdd([1, 0, 1, 0, 0, 1, 1]) → [0, 0, 0, 1, 1, 1, 1] evenOdd([3, 3, 2]) → [2, 3, 3] evenOdd([2, 2, 2]) → [2, 2, 2] 
public int[] evenOdd(int[] nums) {

  int l = nums.length;

  if(l<2)
  return nums;

  int j=l-1;
  for(int i=0;i<l;i++)
  {
    if(nums[i]%2==1)
    {
      while(j>i && nums[j]%2!=0) {
          j--;
      }         
      int t=nums[i];
      nums[i]=nums[j];
      nums[j]=t;

      j--;           
    }  
  }   
  return nums;
}

You're actually super close. 你真的超级亲密。 If you just wrap this code that you have: 如果仅包装以下代码,则您拥有:

int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
j--;

inside of an if 如果一个

if (j > i)

your code actually works. 您的代码实际有效。

As order of array doesn't matter and you need only one loop, you can try below function, 由于数组的顺序无关紧要,并且只需要一个循环,因此您可以尝试以下函数,

public int[] evenOdd(int[] nums) {
    if (nums.length < 2) return nums;

    int[] result = new int[nums.length];
    int even = 0;
    int odd = nums.length - 1;

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] % 2 == 0)
            result[even++] = nums[i];
        else
            result[odd--] = nums[i];
    }
    return result;
}

Not sure if this is "cheating", but you could create 2 arrays, 1 to hold the evens and 1 to hold the odds. 不知道这是否“作弊”,但是您可以创建2个数组,其中1个保留偶数,而1个保留赔率。 In your loop, you would copy all the numbers of each value to their even or odd array, and then after the loop, join/merge the arrays together in a new array and return the new array. 在循环中,您需要将每个值的所有数字复制到其偶数或奇数数组中,然后在循环之后,将数组合并/合并到一个新数组中并返回新数组。

If performance is not too important, you could use a stream: 如果性能不太重要,则可以使用流:

static int[] evenOdd(int[] nums) {
    return Arrays.stream(nums)
            .boxed()
            .sorted(Comparator.comparingInt(i -> i % 2))
            .mapToInt(i -> i)
            .toArray();
}

Unfortunately, IntStream doesn't have a sorted method that takes a Comparator (only a parameterless method , that's why you have to box and unbox to use Stream.sorted(Comparator) . 不幸的是, IntStream没有采用Comparatorsorted方法(只有无parameterless method ,这就是为什么必须装箱和拆箱才能使用Stream.sorted(Comparator)

Here is a code that takes O(N) time and O(1) space to accomplish your task. 这是花费O(N)时间和O(1)空间来完成任务的代码。 I apologise for the Python code. 我为Python代码道歉。

arr = list(map(int, raw_input().split()))

i = 0
j = len(arr) - 1

while i<j:
    if arr[i]%2 != 0 and arr[j]%2 == 0:
        t = arr[i]
        arr[i] = arr[j]
        arr[j] = t
        i = i + 1
        j = j -1

    elif arr[i]%2 == 0 and arr[j]%2 == 0:
        i = i + 1

    elif arr[i]%2 == 0 and arr[j]%2 != 0:
        j = j - 1

    else:
        j = j - 1

print arr

Explanation : The code logic is quite self explanatory. 说明 :代码逻辑很容易说明。 We have two counters, i starting from left end and j starting from right end. 我们有两个计数器, i从左端开始, j从右端开始。 If the left counter is pointing to an even then we just increment it, as it is in its correct place. 如果左计数器指向一个even那么我们将其递增,因为它位于正确的位置。 [Remember you want to shift evens to the left. [请记住,您想将偶数向左移动。 So this even is already in the left side of the array.So we just increment i ]. 所以这甚至已经在数组的左边了,所以我们只增加i ]。 Please look at the code logic to find out what actions are taken based on the current pointers on an even or an odd element. 请查看代码逻辑,以基于偶数或奇数元素上的当前指针找出要采取的操作。

For example: 例如:

If we find i pointing to an odd and j pointing to an `even, then we swap and move both pointers. 如果我们发现i指向一个oddj指向一个偶数,那么我们交换并移动两个指针。 This is understandable, I hope 我希望这是可以理解的

The above solution is in-place and takes O(1) space and O(N) time... Hope this helps!! 上面的解决方案是就地的,占用O(1)空间和O(N)时间...希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM