704:
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
提示:
- 你可以假设 nums 中的所有元素是不重复的。
- n 将在 [1, 10000]之间。
- nums 的每个元素都将在 [-9999, 9999]之间。
首先先自己写了一遍,没有看文章:
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size()-1;
while(left<=right){
int middle = (left+right)/2;
if(target> nums[middle]){
left=middle+1;
}
else if(target < nums[middle]){
right = middle-1;
}
else{
return middle;
}
}
return -1;
}
};
然后发现一个问题,while加不加 =.
然后通过看文章,分析了一下左闭右闭, 和左闭右开的区别。左闭右闭不会考虑middle,所以在while的时候要加上相等的情况,而左闭右开的时候,middle的情况会被考虑上.因此写这种二分法的题目时候,要注意使用一种(偏好左闭右闭)
27:
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.
这道题的暴力解没有什么难点:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
for (int i = 0; i < size; i++) {
if(nums[i] == val){
for(int j =i+1; j<nums.size();j++){
nums[j-1] = nums[j];
}
size--;
i--;
}
}
return size;
}
};
然后是双指针法(两个指针同时走,如果遇到了目标元素,则慢指针停一次,但是快指针是一直在for loop 里面走的!!!:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowpoint = 0;
for(int quickpoint = 0; quickpoint <nums.size() ;quickpoint++){
if(val!=nums[quickpoint]){
nums[slowpoint] = nums[quickpoint];
slowpoint++;
}
}
return slowpoint;
}
};
977.
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int k = A.size() - 1;
vector<int> result(A.size(), 0);
for (int i = 0, j = A.size() - 1; i <= j;) { // 注意这里要i <= j,因为最后要处理两个元素
if (A[i] * A[i] < A[j] * A[j]) {
result[k--] = A[j] * A[j];
j--;
}
else {
result[k--] = A[i] * A[i];
i++;
}
}
return result;
}
};