【Search in Rotated Sorted Array II 】cpp
2015-06-14 12:54
525 查看
题目:
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.
代码:
tips:
通过这题熟悉了stl将vector去重的方法。
采用了偷懒的做法:
1. 先利用stl的unqiue把数组去重
2. 再按照Search in Rotated Sorted Array这题的方法进行二分查找。
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.
代码:
class Solution { public: bool search(vector<int>& nums, int target) { nums.erase(std::unique(nums.begin(), nums.end()),nums.end()); int begin=0, end=nums.size()-1; while ( begin<=end ) { int mid = (begin+end)/2; if ( nums[mid]==target ) return true; // first half sorted if ( nums[begin]<=nums[mid] ) { if ( target>nums[mid] ) { begin = mid+1; } else { if ( target>=nums[begin] ) { end = mid-1; } else { begin = mid+1; } } continue; } // second half sorted if ( nums[mid]<nums[end] ) { if ( target<nums[mid]) { end = mid-1; } else { if ( target<=nums[end]) { begin = mid+1; } else { end = mid-1; } } } } return false; } };
tips:
通过这题熟悉了stl将vector去重的方法。
采用了偷懒的做法:
1. 先利用stl的unqiue把数组去重
2. 再按照Search in Rotated Sorted Array这题的方法进行二分查找。
相关文章推荐
- C/C++中##与#的使用
- c语言中如何实现可变参数
- C语言中通过按位与求奇偶源码
- 【leetcode c++】14Longest Common Prefix
- _int64 C语言中怎么用
- C++ 虚析构函数 分析
- C/C++程序员面试易错题
- C++精确计算代码执行时间精度微秒级
- c++ 模板联系4
- c++ 模板联系4
- c++ 模板练习2
- C++ 一般模板友元关系
- C++ 一般模板友元关系
- c++ 模板练习2
- C++ 模板练习1
- C++ 模板练习1
- Effective C++条款03解读:尽可能使用const
- c++中调用cygwin/x使用ncl
- HDU-1048-The Hardest Problem Ever(C++ && 偶尔一水......)
- C++:模板实参推断及引用折叠