LeetCode33. Search in Rotated Sorted Array
来源:互联网 发布:yum预付卡章程 编辑:程序博客网 时间:2024/06/07 03:37
题目
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.
思路
首先要观察这个数组的特点,即这个数组的分布是分两段的曾序列,满足这样的特点——{mid,...max,min,...submid},这里我用submid来表示次中等大的元素。
那么我们首先拿target跟首元素比较,也就是mid;如果target > mid , 那么我们从头开始寻找;如果target < mid,那么我们从尾端开始倒着寻找(这样可以提高平均效率);由于题目说明没有重复,那么找的次数最多也就是 |target - mid| ,如果还没找到,那就意味着不在数组里头了;
最后注意下标不要越界即可。
代码
public class Solution { public int search(int[] nums, int target) { int length = nums.length; if(length < 1) return -1; if(target == nums[0]) return 0; int cha = target - nums[0]; if(cha > 0){ for(int i = 1 ; i <= cha && i < length; ++ i){ if(nums[i] == target) return i; if(nums[i] - nums[i-1] < 0) return -1; } return -1; } else{ int j = length - 1; if(nums[j] == target) return j; -- j; for( ; j >= j + cha && j >= 0 ; -- j){ if(nums[j] == target) return j; if(nums[j] > nums[j + 1]) return -1; } return -1; } }}
阅读全文
0 0
- [LeetCode33]Search in Rotated Sorted Array
- Leetcode33 Search in Rotated Sorted Array
- leetcode33---Search in Rotated Sorted Array
- leetcode33. Search in Rotated Sorted Array
- [leetcode33] Search in Rotated Sorted Array
- leetcode33~Search in Rotated Sorted Array
- leetcode33~Search in Rotated Sorted Array
- leetcode33~Search in Rotated Sorted Array
- leetcode33. Search in Rotated Sorted Array
- LeetCOde33. Search in Rotated Sorted Array
- LeetCode33. Search in Rotated Sorted Array
- leetcode33 Search in Rotated Sorted Array
- LeetCode33——Search in Rotated Sorted Array
- LeetCode33. Search in Rotated Sorted Array java solution
- leetcode33题解_Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Learning with local and global consistency阅读报告NIPS2003
- 信息安全
- 数据库编程时需要注意的两点!
- 第三方JS库
- 输入一个链表,从尾到头打印链表每个节点的值。
- LeetCode33. Search in Rotated Sorted Array
- An Easy Physics Problem (hdu5572) 2015ACM/ICPC亚洲区上海站
- 单例模式
- 欢迎使用CSDN-markdown编辑器
- 线程安全的误解: 线程安全并不是否定资源共享
- 算法--二叉树
- java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
- 对MFC中CDocument::UpdateAllViews的理解
- python中的random模块