LeetCode 33. 搜索旋转排序数组
题目描述
整数数组 nums 按升序排列,数组中的值 互不相同 。
在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。
给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 。
原题连接
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array
一、基础框架
class Solution {
public int search(int[] nums, int target) {
}
}
二、解题报告
1.思路分析
1、属于查找问题,看到有序优先使用二分查找
2、hash查找效率也可以接受
2.时间复杂度
O(n)
3.代码示例
tips:注意先放进map最开始的值 可以防止target == nums[0] 的状况
class Solution {
public int search(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i ++){
map.put(nums[i],i);
if(map.containsKey(target)){
return map.get(target);
}
}
return -1;
}
}
2.知识点
水题 ,洒洒水的完成了