首页 > 其他分享 >LeetCode #283 移动零(双指针版本,效率高)

LeetCode #283 移动零(双指针版本,效率高)

时间:2023-04-12 15:23:20浏览次数:33  
标签:right 效率高 nums int 元素 283 left LeetCode 指针

基本思路

  思路————双指针
  初始状态左右指针都指向数组首位元素,然后right指针开始迭代数组,当碰到非0元素则与左指针left所在位置的元素交换。
  交换完毕后,左指针left则向前移动到下一位置,做好准备迎接下一个非0元素的交换。
  这种算法效率比之前撰写的“伪双指针”效率更高,更能应对特殊情况。

标程

 1 class Solution {
 2 public:
 3     void moveZeroes(vector<int>& nums) {
 4         int n = nums.size();
 5         int left = 0, right = 0;
 6         while(right < n){
 7             if(nums[right]){
 8                 swap(nums[left++],nums[right]);
 9             }
10             right++;
11         } 
12     }
13 };

时间复杂度

  O(N)

标签:right,效率高,nums,int,元素,283,left,LeetCode,指针
From: https://www.cnblogs.com/miracle-cst/p/17309904.html

相关文章

  • LeetCode #414 第三大的数
    解题思路数组从大到小排序后,从第2个元素开始遍历,如果与上一个元素不相同,则标志位++,标志位一旦从1加到3(两次)则代表存在第三大的数,即可返回。如若不存在第三大的数,则在遍历结束后,函数末尾返回数组的第一个元素(最大的元素)。标程1classSolution{2public:3intthirdMa......
  • LeetCode #485 最大连续 1 的个数
    解题思路基础题,最后加一个特殊情况处理就好,时间复杂度O(n)代码  classSolution{public:intfindMaxConsecutiveOnes(vector<int>&nums){intcount=0;intMaxcount=0;for(inti=0;i<nums.size();i++){if(nums[i]==1){......
  • #yyds干货盘点# LeetCode面试题:矩阵置零
    1.简述:给定一个 mxn的矩阵,如果一个元素为0,则将其所在行和列的所有元素都设为0。请使用原地算法。 示例1:输入:matrix=[[1,1,1],[1,0,1],[1,1,1]]输出:[[1,0,1],[0,0,0],[1,0,1]]示例2:输入:matrix=[[0,1,2,0],[3,4,5,2],[1,3,1,5]]输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]......
  • 4月11日leetcode练习
    设计一个支持push,pop,top操作,并能在常数时间内检索到最小元素的栈。实现MinStack类:MinStack()初始化堆栈对象。voidpush(intval)将元素val推入堆栈。voidpop()删除堆栈顶部的元素。inttop()获取堆栈顶部的元素。intgetMin()获取堆栈中的最小元素。 来源:力扣(Le......
  • leetcode 183
    从不订购的客户 selectc.NameasCustomersfromCustomerscleftjoinOrdersoonc.Id=o.CustomerIdwhereo.CustomerIdisnull selectcustomers.namecustomersfromcustomerswherecustomers.idnotin(selectorders.customeridfromorders) ......
  • leetcode 181
    超过经理收入的员工 selecte1.nameasEmployeefromEmployeee1,Employeee2wheree1.managerId=e2.idande1.salary>e2.salary selecte1.nameasEmployeefromEmployeee1leftjoinEmployeee2one1.managerId=e2.idwheree1.salary>e2.salary......
  • 【LeetCode回溯算法#extra01】集合划分问题【火柴拼正方形、划分k个相等子集、公平发
    火柴拼正方形https://leetcode.cn/problems/matchsticks-to-square/你将得到一个整数数组matchsticks,其中matchsticks[i]是第i个火柴棒的长度。你要用所有的火柴棍拼成一个正方形。你不能折断任何一根火柴棒,但你可以把它们连在一起,而且每根火柴棒必须使用一次。如......
  • [LeetCode] 2390. Removing Stars From a String
    Youaregivenastring s,whichcontainsstars *.Inoneoperation,youcan:Chooseastarin s.Removetheclosest non-star charactertoits left,aswellasremovethestaritself.Return thestringafter all starshavebeenremoved.Note:Thei......
  • 差分数组-leetcode1094
    车上最初有 capacity 个空座位。车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向)给定整数 capacity 和一个数组 trips , trip[i]=[numPassengersi,fromi,toi] 表示第 i 次旅行有 numPassengersi 乘客,接他们和放他们的位置分别是 fromi 和 toi 。这些位......
  • leetcode_打卡1
    leetcode_打卡1题目:1768.交替合并字符串解答:思路:模拟即可,字符串的提取:a.charAt(i)classSolution{publicStringmergeAlternately(Stringword1,Stringword2){Stringresult="";intm=word1.length();intn=word2.length();......