題目描述:
https://leetcode.com/problems/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,7]
might 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.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2]
, target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2]
, target = 3
Output: -1
代碼解答:
package com.jack.algorithm;
import sun.security.util.Length;
/**
* create by jack 2019/5/4
*
* @author jack
* @date: 2019/5/4 20:46
* @Description:
*/
public class SearchInRotatedSortedArray {
/**
* 33-題目描述:
* https://leetcode.com/problems/search-in-rotated-sorted-array/
* @param nums
* @param target
* @return
*/
public static int search(int[] nums, int target) {
int index = -1;
for(int i=0,length = nums.length;i<length;i++){
if (target == nums[i]) {
index = i;
break;
}
}
return index;
}
public static void main(String[] args) {
//數組
int[] nums = {4,5,6,7,0,1,2};
//int[] nums = {4,5,6,7,0,1,2};
//目標值
int target = 0;
//int target = 3;
int index = search(nums,target);
System.out.println("index="+index);
}
}
源碼: