【问题标题】:how to keep rotation count in an array?如何在数组中保持旋转计数?
【发布时间】:2018-01-31 18:33:42
【问题描述】:

给定一个整数数组,该数组已排序(按升序)并已按顺时针方向旋转了某个数字 k。找到并返回 k。 我写的代码如下.. 我得到了错误的结果。

public class CheckRotation {    

    public static int arrayRotateCheck(int[] arr){
        /* Your class should be named CheckRotation
         * Don't write main().
         * Don't read input, it is passed as function argument.
         * Return output and don't print it.
         * Taking input and printing output is handled automatically.
         */
      int s=0;
      int next=0;
      int prev=0;
      int mid=0;
      int n = arr.length-1;
      while(s<=n)
      {
        mid=  s+(n-s)/2;
        next=(mid+1)%n;
        prev=(mid-1)%n;
        if(arr[s]<=arr[n])
        { 
          return s;
        }
        if(arr[mid]<=next && arr[mid]<=prev)
       {
         return mid;
       }

        if(arr[mid]<arr[n])
               n= mid-1;
        if(arr[mid]>arr[s])
          s= mid +1;

      }
      return Integer.MAX_VALUE;
    }
}

【问题讨论】:

  • 您的输入、当前输出和预期输出是什么?看起来很有可能在第一次迭代时返回 s,这将是 0。您可能需要重新考虑您的算法,它看起来类似于二进制搜索,而线性可能更容易和更直接

标签: java arrays counter


【解决方案1】:

如果我正确理解了您的问题,如果一个什锦数组顺时针旋转,所有元素都会向左移动。所以基本上[1, 2, 3, 4] 变成了[2, 3, 4, 1]。你试图找到k 是它被移动的号码。在该示例中,它将是 1。如果是这样,这里有一个解决方案:

public static int RotationCheck(int[] numArray) {
    int smallest = Integer.MAX_VALUE;
    int k = 0;

    //Finding the smallest int
    for(int num: numArray) {
        if(smallest > num)
            smallest = num;
    }

    //Getting new index of smallest int
    for(int i=0;i<numArray.length;i++) {
        if(numArray[i] == smallest)
            k = numArray.length - i;
    }

    return k;
}

我首先找到最小值,然后检查它在数组中的位置。由于数组已排序,因此最小的数字最初将是第一个索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多