Leetcode 33. Search in Rotated Sorted Array (Hard) (cpp)
2016-07-12 11:50
453 查看
Leetcode 33. Search in Rotated Sorted Array (Hard) (cpp)
Tag: Array, Binary Search
Difficulty: Hard
Tag: Array, Binary Search
Difficulty: Hard
/* 33. Search in Rotated Sorted Array (Hard) 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 first = 0, last = nums.size() - 1; while (first != last) { int mid = first + (last - first) / 2; //分半 if (nums[mid] == target) { return mid; } else if (nums[first] <= nums[mid]) { if (nums[first] <= target && target < nums[mid]) { last = mid; } else { first = mid + 1; } } else { if (nums[mid] < target && target <= nums[last]) { first = mid + 1; } else { last = mid; } } } if (nums[first] == target) { return first; } return -1; } };
相关文章推荐
- Leetcode 80. Remove Duplicates from Sorted Array II (Medium) (cpp)
- C++中的单例模式(懒汉、饿汉)
- BJOI2011 严格次小生成树 解题报告
- C++软件工程师,你该会什么?
- C++软件工程师,你该会什么?
- Leetcode 205. Isomorphic Strings (Easy) (cpp)
- Leetcode 118. Pascal's Triangle (Easy) (cpp)
- Leetcode 119. Pascal's Triangle II (Easy) (cpp)
- Leetcode 27. Remove Element (Easy) (cpp)
- C++11多线程系列第一部分
- C++ split 分割字符串
- C++ #pragma 用法小结
- Leetcode 26. Remove Duplicates from Sorted Array (Easy) (cpp)
- JNI使用实例之C、C++ DLL回调java成员函数
- 串算法 - 蛮力匹配 Brute Force
- 《C++ Primer Plus》12.7 队列模拟 学习笔记
- C语言入门(十二)函数的定义和调用
- C++函数模板深入理解1
- Leetcode 3. Longest Substring Without Repeating Characters (Medium) (cpp)
- c++继承