LeetCode_OJ【33】Search in Rotated Sorted Array
2015-10-19 16:23
302 查看
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
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.
这个题目用暴力搜索也能一次过,不过时间复杂度太高。
看tag有二分查找就按照二分查找写,总是有错误。最后看了下别人的代码,将mid =( start + last) / 2 改为 mid =( start + last +1) / 2 之后就通过了,至于问题出在哪里我也不是太清楚。
Java实现如下:
(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.
这个题目用暴力搜索也能一次过,不过时间复杂度太高。
看tag有二分查找就按照二分查找写,总是有错误。最后看了下别人的代码,将mid =( start + last) / 2 改为 mid =( start + last +1) / 2 之后就通过了,至于问题出在哪里我也不是太清楚。
Java实现如下:
public class Solution { public int search(int[] nums, int target) { if(nums == null) return -1; for(int start = 0,last = nums.length -1;start <= last ; ){ int middle = (start + last +1)/2; if(target == nums[middle]) return middle; if(nums[middle] > nums[start]){ if(target < nums[middle] && target >= nums[start]) last = middle -1; else start = middle +1; } else{ if(target > nums[middle] && target <= nums[last]) start = middle +1; else last = middle -1; } } return -1; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解