【问题标题】:"Removing" even numbers from array and moving odd to the front从数组中“删除”偶数并将奇数移到前面
【发布时间】:2017-03-05 21:11:46
【问题描述】:

首先 - 这不是家庭作业 - 我在上次面试时遇到了这个问题,但没能完成。

所以问题类似于:“给定长度为 n 的 int 数组 k,'删除'所有偶数并将奇数移到前面”。它的措辞有点奇怪,因为他们说删除,但例子表明我应该把所有奇数放在数组前面(从 0 索引开始),偶数可以留在数组中(或者不 - 没关系) 在所有奇数之后。 示例:

{1, 4, 6, 8, 7, 2} -> {1, 7, whatever}
{2, 4, 6, 9, 5} -> {9, 5, whatever}

我希望尽可能高效。我无法使用任何其他库或临时数组。

到目前为止得到了这个但我卡住了:

private static void removeEven(int[] k, int n) {
for (int i = 0; i < n; i++) {
  if (k[i] % 2 == 0) {
    k[i] = // don't know
  }
}

【问题讨论】:

  • 必须是同一个数组。

标签: java arrays


【解决方案1】:

解决办法如下:

 private static int[] removeEven(int[] k, int n) {
            for (int i = 0; i < n; i++) {
              if (k[i] % 2 == 0) {
                  for(int j=i+1; j<n; j++){
                      if(k[j] % 2 != 0){
                          k[i] = k[i] + k[j];
                          k[j] = k[i] - k[j];
                          k[i] = k[i] - k[j];
                          break;//if we get a odd number then we swap it with the even one and so we need not need to proceed the inner loop as the k[i] is already swaped with an oddd number
                      }
                  }
              }
            }
            return k;
         }

【讨论】:

    【解决方案2】:

    我想你需要在循环内有一个计数器来记住返回数组的位置。 我已经使用了这段代码,将所有剩余的数组位置设为 0。

    private static void removeEven(int[] k, int n) {
        int counter = 0;
        for (int i = 0; i < n; i++) 
            if (k[i] % 2 == 1)
                k[counter++] = k[i];
        for (int i=counter; i<n; i++)
            k[i] = 0;
    }
    

    我希望这能回应你的回答!

    【讨论】:

    • 你把偶数放在前面!!
    • 不,我正在删除偶数并将奇数放在前面。请尝试执行我的代码,结果将与您要求的相同!
    【解决方案3】:

    我将反转该方法,我的意思不是删除偶数,而是将奇数移到前面,这是他们的意思,他们不关心数组中剩下的内容,所以我的方法就像

    private static int moveOddToFront(int[] k) {
        int frontIndex = 0;
        for (int i = 0; i < k.length; i++) {
            boolean isOdd = k[i] % 2 != 0;
            if (isOdd) {
                k[frontIndex] = k[i];
                frontIndex++;
            }
        }
    
        int newSize = frontIndex;
        return newSize;
    }
    

    【讨论】:

    • 抱歉,这行不通。我用 { 5, 4, 3, 8, 6, 4, 9, 7,6 } 测试它,结果是 { 5, 3, 9, 7, 6, 4, 9, 7, 6 }。
    • 如果您查看原始数组,您会看到您有 4 个奇数,在调用后它们被放置在数组的前面,新的大小将是 4,问题是 {odd numbers , 随便}
    • 我希望正确答案涵盖所有数组长度,而不仅仅是上面给出的那个。反正现在已经不重要了。
    • 我真的不明白这个答案有什么问题,如果困扰你的是数组的其余部分,那么你可以将它们设为 0 或其他什么,问题说它不在乎数组的其余部分。请进一步澄清
    • 好的,如果您完全忽略偶数元素,您的解决方案将有效。我看到有些解决方案没有忽略偶数元素。
    【解决方案4】:

    我想我只会维护两个指向数组中位置的变量。一个将指向下一个偶数(从开头开始),一个将指向下一个奇数(从末尾开始)。当下一个偶数的索引低于下一个奇数时,交换它们。这是工作和测试的代码:

    public static void main(String[] args) {
        int[] test = {2, 4, 6, 9, 5};
        int currentEven = -1;
        int currentOdd = test.length;
        while (currentEven < currentOdd) {
            currentEven = nextEvenIndex(currentEven + 1, test);
            currentOdd = nextLastOddIndex(currentOdd - 1, test);
    
            if (currentEven < currentOdd) {
                swap(currentOdd, currentEven, test);
            }
        }
    
        for (int i = 0; i < test.length; i++) {
            System.out.print(test[i]);
        }
    }
    
    private static int nextEvenIndex(int start, int[] array) {
        while (start < array.length) {
            if (array[start] % 2 == 0) {
                return start;
            }
            start++;
        }
        return -1;
    }
    
    private static int nextLastOddIndex(int start, int[] array) {
        while (start >= 0) {
            if (array[start] % 2 == 1) {
                return start;
            }
            start--;
        }
        return -1;
    }
    
    private static void swap(int index1, int index2, int[] array) {
        int swap = array[index1];
        array[index1] = array[index2];
        array[index2] = swap;
    }
    

    这是 O(n),这是我认为您可以在这里获得的最佳性能。

    这也比这里的许多其他答案表现得更好,因为一个数字永远不会交换两次;也就是说,大多数其他解决方案都会迭代整个数组(有时会进行不必要的交换),而这只迭代了一半。

    【讨论】:

      【解决方案5】:

      类似下面的伪代码怎么样,它将首先返回奇数数组,偶数数组最后,并保留奇数子集和偶数子集的原始顺序。

      if array.length < 2 
        return array
      else
        p=0
        while array[p].odd and p < array.length
          p++
        q = p+1
        if q < array.length
          repeat
            if array[q].odd
              swap(array,p,q) p++ q++
            else
              q++
          until q >= array.length
      

      【讨论】:

        【解决方案6】:

        您可以使用一个临时变量来放置要移动的值,而不是使用另一个变量来设置放置要移动的值的位置。

        代码:

        for (int i = 0, j = 0; i < n; i++) {
                if (k[i] % 2 != 0 ) {
                    int tempInt = k[j];
                    k[j] = k[i];
                    k[i] = tempInt;
                    j++;
                }
            }
        

        【讨论】:

          【解决方案7】:

          使用下面的代码,我们甚至可以从数组中删除所有内容并写入其余数组。

          public static void main (String[] args) {
                  int a[]={7,9,7,8,4};
          
                  for(int i=0;i<a.length;i++){
                      boolean x=false;
                      if(a[i]%2==0){
                          x=true;
                      }
                      if(!x){
                          System.out.println(a[i]);
                      }
                  }
          
              }
          

          【讨论】:

            【解决方案8】:

            一个简单的python解决方案,

            def moveEven(arr):
                start, end = 0, len(arr)-1
                while start <= end:
                    if arr[start] % 2 == 0:
                        arr[start], arr[end] = arr[end], arr[start]
                        end -= 1
                    else:
                        start += 1
            

            【讨论】:

              【解决方案9】:

              我的解决方案将所有奇数放在数组的前面,其余位置为零。

              测试用例:

              int[] array1 = { 1, 4, 6, 8, 7, 2 };
              int[] array2 = { 2, 4, 6, 9, 5 };
              
              reverse(array1,6);  // result: [1, 7, 0, 0, 0, 0]
              reverse(array2,5);  // result: [9, 5, 0, 0, 0]
              

              代码:

              public static void reverse(int[] array, int N) {
                  if (N < 2) {
                      return;
                  }
                  int index = 0;  // index at which the next odd number should be placed
                  for (int i = 0; i < N; i++) {
                      if (array[i] % 2 == 1) {
                          array[index] = array[i];
                          if (i > index) {
                              array[i] = 0;
                          }
                          index++;
                      } else {
                          array[i] = 0;
                      }
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 2017-02-06
                • 2016-01-27
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-08-11
                • 2019-12-31
                • 1970-01-01
                相关资源
                最近更新 更多