leetcode题目 旋转排序数列的查找
2015-10-05 18:03
375 查看
题目: 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.
思路: 普通的二分查找只有两种情况,而旋转数列的查找则有6种情况,分情况移动前后指针即可。当然,递归也可以实现。
运行时间4ms,测试结果虽然只击败了12%的代码,但是看到大家都集中在4ms附近。
(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.
思路: 普通的二分查找只有两种情况,而旋转数列的查找则有6种情况,分情况移动前后指针即可。当然,递归也可以实现。
class Solution { public: int search(vector<int>& nums, int target) { int fir=0; int sec=nums.size()-1; int mid=0; bool Isfront=false; if(target>=nums[0]) Isfront=true; while(fir>=0&&sec>=0&&fir<nums.size()&&sec<nums.size()&&fir<=sec) { mid=(fir+sec)/2; if(nums[mid]>=nums[0]) { if(nums[mid]<target) { fir=mid+1; continue; } else if(nums[mid]>target) { if (Isfront) { sec = mid - 1; continue; } else { fir = mid + 1; continue; } } else return mid; } else { if(nums[mid]<target) { if(Isfront) { sec=mid-1; continue; } else { fir=mid+1; continue; } } else if(nums[mid]>target) { sec=mid-1; continue; } else return mid; } } return -1; } };
运行时间4ms,测试结果虽然只击败了12%的代码,但是看到大家都集中在4ms附近。
相关文章推荐
- 测试自定义随笔样式
- Java序列化的机制和原理
- 算法-低位优先的字符串排序
- Gson解析(6)——注册TypeAdapter及处理Enum类型
- iOS编程--------UIControl的作用及其子类UISegmentedControl的使用 / UISlider的使用 / UIImageView的使用
- 间接赋值从0级指针到1级指针
- 工作总结概述
- 白话谈谈最近进入个人淘宝的....
- Java Callable测试
- 我的XPath笔记
- HDU 5002 Tree LCT 区间更新
- C#--索引
- Gson解析(5)——实际开发中的特殊需求处理
- Hbase 源码分析之 Regionserver上的 Get 全流程
- Hadoop命令大全
- 二维码的生成
- 【总结】Java基础总结⑸
- mybatis调用存储过程实例
- 从输入 URL 到页面加载完成的过程中都发生了什么事情?
- Gson解析(4)——Map处理数据(下)