今日题目 leetcode 704.二分查找、27.移除元素
力扣题目链接704. 二分查找 - 力扣(LeetCode)
C++版本:
// 左闭右闭区间
class Solution{
public:
int search(vector &nums, int target){
int left = 0;
int right = nums.size() - 1;
while(left <= right){
int middle = left + ((right - left) / 2);
if(nums[middle] < target){
left = middle + 1;
}else if(nums[middle] > target){
right = middle - 1;
}else{
return middle;
}
}
// 没有找到目标值
return -1;
}
};
int main(){
vector nums{-1,0,3,5,9,12}; // 变长数组定义和赋值
int target = 9;
Solution sol;
int getIndex = sol.search(nums, target);
std::cout << getIndex << std::endl; // 输出 4
}
#include
using namespace std;
// 左闭右开区间
class Solution{
public:
int search(vector &nums, int target){
int left = 0;
int right = nums.size(); // 左闭右开区间,不包括最右边的值,所以最右的值定义为长度
while(left < right){ // 不使用=号
int middle = left + ((right - left) >> 1); // 右移1位等于除以2
if(nums[middle] > target){
right = middle;
}else if(nums[middle] < target){
left = middle + 1;
}else{
return middle;
}
}
// 没有找到目标值
return -1;
}
};
int main(){
vector nums{-1,0,3,5,9,12}; // 变长数组定义和赋值
int target = 9;
Solution sol;
int getIndex = sol.search(nums, target);
std::cout << getIndex << std::endl; // 输出 4
}
Python版本:
class Solution:
def search(self, nums, target) -> int:
left, right = 0, len(nums) - 1
while left <= right:
middle = left + ((right - left) // 2)
if nums[middle] > target:
right = middle - 1
elif nums[middle] < target:
left = middle + 1
else:
return middle
return -1
nums = [-1, 0, 3, 5, 9, 12]
target = 9
sol = Solution()
print(sol.search(nums, target))
# 左闭右开
# 左闭右开
class Solution:
def search(self, nums, target) -> int:
left, right = 0, len(nums)
while left < right:
middle = left + ((right - left) // 2)
if nums[middle] > target:
right = middle
elif nums[middle] < target:
left = middle + 1
else:
return middle
return -1
nums = [-1, 0, 3, 5, 9, 12]
target = 9
sol = Solution()
print(sol.search(nums, target))
移除元素 移除元素力扣链接
C++版本
// 暴力解法
// 时间复杂度 O(n^2)
// 空间复杂度 O(1)
class Solution{
public:
int removeElement(vector& nums, int val){
int size = nums.size();
for(int i = 0; i < size; i++){
if(nums[i] == val){ // 如果等于需要移除的元素,整体前移一位
for(int j = i+1; j < size; j++){
nums[j-1] = nums[j];
}
i--;
size--;
}
}
return size;
}
};
int main(){
vector inums{0,1,2,2,3,0,4,2}; // 变长数组定义和赋值
int val = 2;
Solution sol;
int newSize = sol.removeElement(inums, val);
for(int i = 0; i
// 双指针法
// 时间复杂度:O(n)
// 空间复杂度:O(1)
class Solution{
public:
int removeElement(vector& nums, int val){
int slowIndex = 0;
for(int fastIndex=0; fastIndex < nums.size(); fastIndex++){
if(val != nums[fastIndex]){
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};
Python版本(双指针)
class Solution:
def removeElement(self, nums, val):
fast, slow = 0, 0
size = len(nums)
while fast < size:
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
nums = [0, 1, 2, 2, 3, 0, 4, 2]
val = 2
rem = Solution()
length = rem.removeElement(nums, val)
print(f"新的长度:{length}", nums)
最后输出为:新的长度:5 [0, 1, 3, 0, 4, 0, 4, 2] 前5个元素为删除对应2后的元素,满足要求