标签:style class blog code java http
1. 查找和排序
1 int Partition(std::vector<int>& vec, int first, int last) 2 { 3 if (first < 0 || last >= vec.size()) { 4 throw invalid_argument("invalid_argument"); 5 } 6 7 int index = RandomInRange(first, last); 8 std::swap(vec.at(index), vec.at(first)); 9 int midIndex = first; 10 for (int i = first + 1; i <= last; ++i) { 11 if (vec.at(i) < vec.at(first)) { 12 swap(vec.at(++midIndex), vec.at(i)); 13 } 14 } 15 std::swap(vec.at(first), vec.at(midIndex)); 16 return midIndex; 17 } 18 19 int RandomInRange(int first, int last) 20 { 21 assert(first <= last); 22 int res = rand() % (last - first + 1) + first; 23 return res; 24 }
1 int FindRotateMin(const std::vector<int>& vec) 2 { 3 if (vec.size() == 0) { 4 throw std::invalid_argument("invalid_argument"); 5 } 6 7 int low = 0; 8 int high = vec.size() - 1; 9 int mid = low; // 如果数组原本有序,返回vec.at(mid)正确 10 while (vec.at(low) >= vec.at(high)) { // 保证 low 总是指向 第一个子数组, high 总是指向 第二个子数组 11 mid = low + (high - low) / 2; 12 if (high - low == 1) return vec.at(high); 13 14 if (vec.at(low) == vec.at(mid) && vec.at(mid) == vec.at(high)) { 15 return *(std::min_element(vec.begin() + low, vec.begin() + high + 1)); 16 } 17 18 if (vec.at(low) <= vec.at(mid)) { 19 low = mid; 20 } 21 22 if (vec.at(mid) <= vec.at(high)) { 23 high = mid; 24 } 25 } 26 return vec.at(mid); 27 }
b. 找出旋转数组的最大值
1 int FindRotateMax(const std::vector<int>& vec) 2 { 3 if (vec.size() == 0) { 4 throw std::invalid_argument("invalid_argument"); 5 } 6 7 int low = 0; 8 int high = vec.size() - 1; 9 int mid = high; 10 while (vec.at(low) >= vec.at(high)) { 11 mid = low + (high - low) / 2; 12 if (high - low == 1) return vec.at(low); 13 14 if (vec.at(low) == vec.at(mid) && vec.at(mid) == vec.at(high)) { 15 return *(std::max_element(vec.begin() + low, vec.begin() + high + 1)); 16 } 17 18 if (vec.at(low) <= vec.at(mid)) { 19 low = mid; 20 } 21 22 if (vec.at(mid) <= vec.at(high)) { 23 high = mid; 24 } 25 } 26 return vec.at(mid); 27 }
c. 查找旋转数组的某个元素
剑指offer (8) 旋转数组,布布扣,bubuko.com
标签:style class blog code java http
原文地址:http://www.cnblogs.com/wwwjieo0/p/3773606.html