两种解法:左闭右闭,左闭右开。重点区间定义。
解法一
class Solution {
public:
int search(vector& nums, int target) {
int len = nums.size();
int a = 0;
int b = len-1;
while (a<=b) //左闭右闭
{
int m = a + ((b-a) / 2); //防止溢出
if (nums[m] > target)
b = m-1;
else if (nums[m] < target)
a = m+1;
else
return m;
}
return -1;
}
};
解法二:
class Solution {
public:
int search(vector& nums, int target) {
int a = 0;
int b = nums.size();
while (a target)
b = m; //右开无需加一
else if (nums[m] < target)
a = m+1;
else
return m;
}
return -1;
}
};
##977
非递减数列,其平方最大值一定在左右两边上。
class Solution {
public:
vector sortedSquares(vector& nums) {
int i = 0;
int j = nums.size()-1;
int k = j;
vector result(j+1, 0);
while (i <= j){
int ti = nums[i]*nums[i];
int tj = nums[j]*nums[j];
if (ti < tj){
result[k--] = tj;
j--;
}
else {
result[k--] = ti;
i++;
}
}
return result;
}
};



