• 154. Find Minimum in Rotated Sorted Array II


    Follow up for "Find Minimum in Rotated Sorted Array":
    What if duplicates are allowed?

    Would this affect the run-time complexity? How and why?

    Suppose an array sorted in ascending order 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.

    The array may contain duplicates.

     与Find Minimum in Rotated Sorted Array类似,可以和nums[left]比,也可以和nums[right]比,代码如下:

     1 public class Solution {
     2     public int findMin(int[] nums) {
     3         if(nums==null||nums.length==0) return -1;
     4         int low = 0;
     5         int high = nums.length-1;
     6         while(low < high) {
     7             int mid = low + (high - low) / 2;
     8             if(nums[low] < nums[high]) return nums[low];
     9             else if(nums[low] < nums[mid]) low = mid + 1;
    10             else if(nums[low] > nums[mid]) high = mid;
    11             else low++;
    12         }
    13         return nums[low];
    14     }
    15 }
    16 // the run time complexity could be two cases. the average case could be logn, the worst case could be O(n), the space complexity could be O(1);

    public class Solution {

        public int findMin(int[] nums) {

            int left=  0;

            int right = nums.length-1;

            while(left<right){

                int mid = left+(right-left)/2;

                if(nums[mid]<nums[right]){

                    right = mid;

                }else if(nums[mid]>nums[right]){

                    left = mid+1;

                }else{

                    right--;

                }

            }

            return nums[left];

        }

    }

  • 相关阅读:
    Java之多线程(实现Runnable接口)
    Java之使用HttpClient发送GET请求
    hbase中文内容编码转换
    Java之utf8中文编码转换
    Java之正则表达式
    Java之List排序功能举例
    maven测试时中文乱码问题解决方法
    Hbase之IP变更后无法启动问题解决
    Hbase远程连接:Can't get the locations
    重启Hbase命令
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6359741.html
Copyright © 2020-2023  润新知