本文主要是介绍Day1:二分查找704 移除元素27,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接704. 二分查找 - 力扣(LeetCode)
int search(vector<int>& nums, int target) {int left = 0;int right = nums.size() - 1;int mid = (right - left) / 2;while (left <= right){if (target == nums[mid]){return mid;}else if (target < nums[mid]){right = mid - 1;}else {left = mid + 1;}mid = (right - left) / 2+left;}return -1;}
题目链接27. 移除元素 - 力扣(LeetCode)
int removeElement(vector<int>& nums, int val) {if(nums.size()==0){return 0;}int left = 0;int right = nums.size() - 1;int count = 0;while (left < right) {while (right>0&&nums[right] == val) {right--;}while (left<nums.size()&&nums[left] != val) {left++;}if (left < right) {swap(nums[left], nums[right]);}}int i = 0;for(auto e:nums){if(e!=val){count++;}}return count;}
最后
要注意数组边界是否越界,还有熟练掌握双指针,多考虑一下测试用例的极端情况,比如传入为空之类的,太久没有写题了手太生了,希望能坚持下去,加油
这篇关于Day1:二分查找704 移除元素27的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!