Search in Rotated Sorted Array
2015-07-02 19:58
513 查看
描述
Suppose a sorted array 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.
中文
轮换排序的数组,给你一个目标值,找到目标值的索引号。
假设数组中没有重复的元素。
分析:
使用二分查找,找到中间值,和起始值进行比较,如果中间值小于起始值,则说明右面有序。否则左面有序,这样继续用二分查找进行。
二分查找算法不熟悉,需要加强训练,边界问题,需要注意
正确的:
Runtime: 8 ms
Suppose a sorted array 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.
中文
轮换排序的数组,给你一个目标值,找到目标值的索引号。
假设数组中没有重复的元素。
分析:
使用二分查找,找到中间值,和起始值进行比较,如果中间值小于起始值,则说明右面有序。否则左面有序,这样继续用二分查找进行。
class Solution { public: int search(vector<int>& nums, int target) { int n; n=nums.size(); if(n==0) return -1; int low,high; low=0;high=n-1; while(low<high) //错误 可以用low!=high作为结束条件 { mid=(low+high)/2;//求中值一定要注意 if(target==nums[mid]) return mid; if(nums[low]<nums[mid]){//用小于等于说明转折点在右半部分 if(targent<nums[mid]) target必须同时限定在两个边界内才可以。 high=mid; esle low=mid; } else{ if(targent>nums[mid]) low=mid; esle high=mid; } } return -1; } };
二分查找算法不熟悉,需要加强训练,边界问题,需要注意
正确的:
class Solution { public: int search(vector<int>& nums, int target) { int first=0; int last=nums.size()-1; int mid; while(first<=last) { mid=(first+last)/2; if(nums[mid]==target) return mid; if(nums[first]<=nums[mid]) { if(target>=nums[first]&&target<nums[mid]) last=mid-1; else first=mid+1; } else { if(target>nums[mid]&&target<=nums[last]) first=mid+1; else last=mid-1; } } return -1; } };
Runtime: 8 ms
相关文章推荐
- MyBatis数据持久化(十一)Mybatis3、Spring4、Struts2整合开发
- 挑逗B少年搞计划10 假设你是愿意用我的心脏层剥离一层~
- 2015比较常用的第三方类库
- Intent意图常见用法
- Linq To SQL LEFT OUTER JOIN (Left Join)
- 在virtualenv中安装libxml2和libxslt
- PS制作太极图
- mysql 端口监听问题
- Java类的克隆
- yate学习--关于yrtpchan模块
- 使程序在Linux下后台运行
- 欢迎使用CSDN-markdown编辑器
- NYOJ 739 笨蛋难题四
- 01背包问题--动态规划解法
- java junit测试
- Android优化工具SparseArray稀疏数组
- 使用指针操作列表时,
- poj2298-Toy Storage-判断点在直线的哪侧
- DL4NLP---第三讲
- jquery基础-包裹 替换 删除 复制