[LeetCode] 33. Search in Rotated Sorted Array
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
class Solution {
//traget 1
// 7 0 1 2 4 5 6
// 4 5 6 7 0 1 2
func search(_ nums: [Int], _ target: Int) -> Int {
var startIndex = 0;
var endIndex = nums.count - 1;
while(startIndex <= endIndex) {
let startValue = nums[startIndex];
let middleIndex = startIndex + (endIndex - startIndex)/2;
let middleValue = nums[middleIndex];
let endValue = nums[endIndex];
if(middleValue == target) {
return middleIndex;
}
else if(middleValue >= startValue) {
if(target >= startValue && target < middleValue) {
// print("target >= startValue && target < middleIndex");
endIndex = middleIndex - 1;
}
else {
//print("target >= startValue && target < middleIndex 222");
startIndex = middleIndex + 1;
}
}
else if(middleValue < startValue) {
//print("midValue <= target");
if(target > middleValue && target <= endValue) {
// print("endValue: \(endValue) && target < middleIndex");
startIndex = middleIndex + 1;
}
else {
// print("endValue: \(endValue) && target < middleIndex 222");
endIndex = middleIndex - 1;
}
}
}
return -1;
}
}Previous[LeetCode] 28. Implement strStr()Next[LeetCode] 34. Find First and Last Position of Element in Sorted Array
Last updated