1、第一道二分题目是模板,比较简单
int search(int* nums, int numsSize, int target){
int left = 0;
int right = numsSize-1;
while(left <= right) {
int mid = (left+right)/2;
if(nums[mid] == target) {
return mid;
}
if(nums[mid] > target) {
right = mid-1;
} else {
left = mid+1;
}
}
return -1;
}
2、第二道有点小技巧,需要简单动手推理一下,考虑到内存和时间限制,只操作一遍即可得到答案
int removeElement(int* nums, int numsSize, int val){
int n = 0;
for(int i = 0; i < numsSize; i++) {
if(nums[i] == val) {
n++;
} else {
nums[i-n] = nums[i];
}
}
return numsSize-n;
}