学习资源:
size()为0的时候,size()-1不是-1而是其他数:
关于vector.size()的一个坑点_vector size_檐廊少主的博客-CSDN博客
vector的insert插入:
C++ STL vector插入元素(insert()和emplace())详解 (biancheng.net)
vector<int> nums = { 1 };
int s = nums.size();
int a = nums.size() - 2;
cout << nums.size() - 2 << endl; // 18446744073709551615
cout << s - 2 << endl; // -1
cout << a << endl; // -1
自己写的:
没有满足O(logN)的时间复杂度。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @return int整型
*/
int findPeakElement(vector<int>& nums) {
// write code here
int s = nums.size();
if(s == 0 || s == 1)
return 0;
if(s == 2)
if (nums[0] < nums[1])
return 1;
else
return 0;
// 3个元素及以上
// 考虑首末端
if(nums[0] > nums[1])
return 0;
if(nums[s-1] > nums[s-2])
return s-1;
// 考虑[1, 5] 一共[0, 6] size = 7
for(int i = 0; i < s - 2; i++){
if (nums[i] < nums[i+1] && nums[i+2] < nums[i+1])
return i+1;
}
return 0; //题目没说,没有山峰返回什么
}
};
刷题模板的:
nums为空,返回-1。
感觉是设计不出来的算法。很巧妙。
考虑了只有两个节点的情况,非常完美。
主要原因是题目只要求找到一个高峰即可,且首尾两端是负无穷,所以一定有高峰。
综上,当mid出现右边是往下的情况时,最坏的情况也就是mid是高峰。
题目的要点在于时间复杂度是O(logN)。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @return int整型
*/
int findPeakElement(vector<int>& nums) {
// write code here
int left = 0;
int right = nums.size()-1;
while(left < right){
int mid = (left + right) / 2;
if(nums[mid] > nums[mid+1])
right = mid;
else
left = mid+1;
}
return right;
}
};