leetcode - 33.Search in Rotated Sorted Array
2017-03-02 19:56
621 查看
Search in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.(i.e.,
0 1 2 4 5 6 7might become
4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Solution1:
public int search(int[] nums, int target) { int length = nums.length; if (length == 0) { return -1; } if (length == 1) { return nums[0] == target ? 0 : -1; } int index = 0; while (index < length - 1 && nums[index] < nums[index + 1]) { index++; } int result = -1; if (index == length - 1) { result = search(nums, 0, length - 1, target); } else if (index == 0) { result = nums[0] == target ? 0 : search(nums, 1, length - 1, target); } else if (nums[index] < target || nums[index + 1] > target) { } else if (nums[0] <= target) { result = search(nums, 0, index, target); } else { result = search(nums, index + 1, length - 1, target); } return result; } private int search(int[] nums, int begin, int end, int target) { if (begin > end) { return -1; } int mid = (begin + end) / 2; int value = nums[mid]; if (value > target) { return search(nums, begin, mid - 1, target); } else if (value == target) { return mid; } else { return search(nums, mid + 1, end, target); } }
Solution2:
better
public int search(int[] A, int target) { if (A.length == 0) { return -1; } int lo = 0; int hi = A.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (A[mid] == target) return mid; if (A[lo] <= A[mid]) { if (target >= A[lo] && target < A[mid]) { hi = mid - 1; } else { lo = mid + 1; } } else { if (target > A[mid] && target <= A[hi]) { lo = mid + 1; } else { hi = mid - 1; } } } return A[lo] == target ? lo : -1; }
相关文章推荐
- LeetCode --- 33. Search in Rotated Sorted Array
- [Leetcode] 33. Search in Rotated Sorted Array
- leetcode 33 -- Search in Rotated Sorted Array
- Search in Rotated Sorted Array - LeetCode 33
- [leetcode 33]Search in Rotated Sorted Array
- 33.search in rotated sorted array leetcode java
- leetcode 33: Search in Rotated Sorted Array
- [leetcode-33]Search in Rotated Sorted Array(C)
- leetcode 33 Search in Rotated Sorted Array
- LeetCode 33 — Search in Rotated Sorted Array(C++ Java Python)
- leetcode[33]Search in Rotated Sorted Array
- [Leetcode 33, Hard] Search in Rotated Sorted Array
- LeetCode(33)Search in Rotated Sorted Array
- [leetcode 33] Search in Rotated Sorted Array
- LeetCode 33 Search in Rotated Sorted Array 二叉查找(三)
- Leetcode[33]-Search in Rotated Sorted Array
- LeetCode(33)Search in Rotated Sorted Array
- LeetCode(33)Search in Rotated Sorted Array
- leetCode 33.Search in Rotated Sorted Array(排序旋转数组的查找) 解题思路和方法
- LeetCode 33, Search in Rotated Sorted Array-----Binary Search