leetcode----81. Search in Rotated Sorted Array II

链接:

https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

大意:

给定一个旋转有序一维数组nums,判断target是否在nums中。注意:nums中含重复的元素。例子:

思路:

本题思路和leetcode33题类似:https://blog.csdn.net/smart_ferry/article/details/88775716

不过在提交code后击败率低得可怜,确实,之前的解法是O(n)的时间复杂度

代码:(非最佳)

class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0 || nums.length == 1 && nums[0] != target)
            return -1;
        int s = 0, e = nums.length - 1;
        if (target > nums[e] && target < nums[s])
            return -1;
        if (target <= nums[e]) {
            while (e > s && nums[e - 1] < nums[e] && target < nums[e]) {
                e--;
            }
            if (nums[e] == target)
                return e;
            else 
                return -1;
        } else {
            while (s < e && nums[s] < nums[s + 1] && target > nums[s]) {
                s++;
            }
            if (nums[s] == target)
                return s;
            else 
                return -1;
        }
    }
}

结果:

结论:

思路有待优化。回想下XXY大佬给我讲解的一个秀的解法。

 

 

猜你喜欢

转载自blog.csdn.net/smart_ferry/article/details/88989463
今日推荐