81. Search in Rotated Sorted Array II
2016-05-06 17:54
405 查看
Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
这个题目是在https://leetcode.com/problems/search-in-rotated-sorted-array/
的基础上,添加了允许有相同的元素这个条件。
那么就会有一种特殊情况,比如1,1,1,1,1,3,3 旋转之后为1,3,3,1,1,1,1.
当中间的元素等于第一个元素时,就把l++,因为target!=nums[mid]的
而nums[mid]=nums[l],可以推出target!=nums[l]。
而 Search in Rotated Sorted Array
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.
这个题目 只需要把返回的参数改一下就可以AC了。
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
这个题目是在https://leetcode.com/problems/search-in-rotated-sorted-array/
的基础上,添加了允许有相同的元素这个条件。
那么就会有一种特殊情况,比如1,1,1,1,1,3,3 旋转之后为1,3,3,1,1,1,1.
当中间的元素等于第一个元素时,就把l++,因为target!=nums[mid]的
而nums[mid]=nums[l],可以推出target!=nums[l]。
class Solution { public: bool search(vector<int>& nums, int target) { int l=0,r=nums.size()-1; while(l<=r){ int mid=(l+r)/2; if(nums[mid]==target) return true; else if(nums[mid]>nums[l]){//递增的序列在左边 if(target>=nums[l]&&target<nums[mid]) r=mid-1; else l=mid+1; }else if(nums[mid]<nums[l]){ if(target>nums[mid]&&target<=nums[r]) l=mid+1; else r=mid-1; }else if(nums[mid]==nums[l]){ l++; } } return false; } };
而 Search in Rotated Sorted Array
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.
这个题目 只需要把返回的参数改一下就可以AC了。
class Solution { public: int search(vector<int>& nums, int target) { int l=0,r=nums.size()-1; while(l<=r){ int mid=(l+r)/2; if(nums[mid]==target) return mid; else if(nums[mid]>nums[l]){ if(target>=nums[l]&&target<nums[mid]) r=mid-1; else l=mid+1; }else if(nums[mid]<nums[l]){ if(target>nums[mid]&&target<=nums[r]) l=mid+1; else r=mid-1; }else if(nums[mid]==nums[l]){ l++; } } return -1; } };
相关文章推荐
- GSM Hacking:使用BladeRF、树莓派、YatesBTS搭建便携式GSM基站
- MYSQL必知必会读书笔记 第十五和十六章 联结表
- Tomcat 优化配置
- SCALA_IDE开发Spark程序
- 数据结构基础知识
- 框架编码为gb2312的项目在传递参数中文无法提交的问题
- JAVA IF判断语句
- ionic保存数据后,后退到列表页并刷新列表
- 循环
- textfield.placeholder居中
- go语言编程(1)--环境搭建liteide--RHEL6.5
- 单例模式---饿汉式
- 倒计时获取验证码
- C# WinForm开发系列 - RDLC
- 获取公网ip地址
- MySQL max_allowed_packet设置及问题
- Physics.Raycast指定碰撞层
- 解决openwrt页面升级中“不支持所上传的文件格式”问题
- NET MVC RazorEngine 解析模板生成静态页
- c#实现清理回收站垃圾