leetcode之Find Minimum in Rotated Sorted Array

题目:

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.

思路:

一开始看错题目,以为是求一趟排序的轴值,于是想到利用快排。代码如下:

public class Solution {
	//利用快排求一趟排序轴值
    public static int findMin(int[] num) {
        int p,i,j;
        p = num[0] ;//轴值
        i = 0;
        j = num.length-1;
        
        while(i < j)
        {
            while(i < j && num[j] >= p)
            {
                j--;
            }
            num[i] = num[j];
            while(i < j && num[i] <= p)
            {
                i++;
            }
            num[j] = num[i];
        }
        num[i] = p;
		System.out.print("\n一趟排序后:");
		for(int x =0 ; x < num.length ; x++)
			System.out.print(" " +num[x]);
        return i;
    }
    


public static void main(String[] args){
    
	  int[] n = new int[]{49,14,38,74,96,65,8,49,55,27};
      System.out.print("待排序数: ");
	  for(int x =0 ; x < n.length ; x++)
			System.out.print(" "+n[x]);
	System.out.println("\n一趟排序的轴值是:"+ Solution.findMin(n));

	}
}

仔细读题,看到关键词 a sorted array 、 is rotated、 at some pivot unknown to you beforehand.

还是没注意到the minimum element.是最小值的意思,即使此时我用有道翻译,知道前几个关键词理解错了,这个minimum我查到是最小值,但是我任然以为是求最中间的值。于是想到折半插入排序,然后遍历最终数组得到中间值。代码如下:

 public class SolutionBinarySort{
//利用折半查找求有序表数组的中间值
	 public static int findMin(int[] num) {
        int high,low,i,j,mid,p;
        
        for(i = 1; i <= num.length-1; i++)
        {
			p = num[i];
            low = 0;
            high = i -1 ;
            while(low <= high)
         {
             mid = (low + high)/2;
             if(num[i] >= num[mid])
                {
                 low = mid + 1;
                }
             else
             high = mid -1;
         }
        
         for(j = i -1; j >= high +1; j--)
         {
             num[j+1] = num[j];
         }
          num [high +1] = p;
		}
		System.out.print("\n折半排序后: ");
		   for(int x =0 ; x < num.length ; x++)
			System.out.print(" " +num[x]);

      return num[(num.length-1)/2];
    }
	
	public static void main(String[] args)
	{
		int a[] = new int[]{5,7,4,9,3};
		//int a[] = new int[]{1,2,3};
		System.out.print("待排序数: ");
		for(int x =0 ; x < a.length ; x++)
			System.out.print(" " +a[x]);
		System.out.print("\n中间值是 " + findMin(a));
	}  
}

最后,实在受不了了,用有道翻译,改了最后的返回值return num[0],拉倒了就。最终ac runtime 412ms.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值