每日一题02

每日一题 双指针算法 leetcode 27 移出元素 https://leetcode.cn/problems/remove-element/ 代码: cpp: class Solution { public: int removeElement(vector<int>& nums, int val) { int fast = 0; int slow = 0; for (fast = 0; fast < nums.size(); fast++){ if(nums[fast] != val){ nums[slow++] = nums[fast]; } } return slow; } }; python: class Solution: def removeElement(self, nums: List[int], val: int) -> int: slow, fast = 0, 0 for fast in range(len(nums)): if nums[fast] != val: nums[slow] = nums[fast] slow += 1 return slow leetcode 26.删除有序数组中的重复项 https://leetcode.cn/problems/remove-duplicates-from-sorted-array/ 代码 cpp: class Solution { public: int removeDuplicates(vector<int>& nums) { int fast; int slow = 0; for(fast = 1; fast < nums.size(); fast++){ if(nums[fast] != nums[slow]){ slow++; nums[slow] = nums[fast]; } } return slow + 1; } }; python: ...

2023年04月03日 · 2 分钟 · 596 字 · ZhaoYang

每日一题01

每日一题 二分查找 leetcode 704 二分查找 https://leetcode.cn/problems/binary-search/ 题解: CPP: 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 >> 1; if(nums[middle] >= target){ right = middle; }else{ left = middle + 1; } } if(nums[left] == target) return left; return -1; } }; 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 + 1 >> 1; if(nums[middle] > target){ right = middle - 1; }else{ left = middle; } } if(nums[left] == target) return left; return -1; } }; python: class Solution: def search(self, nums: List[int], target: int) -> int: left, right = 0,len(nums) - 1 while left < right: middle = left + right + 1 >> 1 if nums[middle] > target: right = middle - 1 elif nums[middle] <= target: left = middle if nums[left] == target: return left return -1 class Solution: def search(self, nums: List[int], target: int) -> int: left, right = 0,len(nums) - 1 while left < right: middle = left + right >> 1 if nums[middle] >= target: right = middle elif nums[middle] < target: left = middle + 1 if nums[left] == target: return left return -1 leetcode 35.搜索插入位置 https://leetcode.cn/problems/search-insert-position/ ...

2023年04月02日 · 3 分钟 · 1028 字 · ZhaoYang