Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
来源:互联网 发布:社会网络分析法软件 编辑:程序博客网 时间:2024/05/01 22:53
题目:
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
思路分析:
题意是给定一个整形的数组,把其中为0的元素移动到数组末尾,但是不改变非零元素的前后位置。
下面的做法是遍历数组,用变量zeronum记录0的个数,同时用pos记录最前一个可写入的位置,把非零的元素依次写入pos的位置。最后将剩余的元素补0。
代码实现(时间复杂度O(n)):
public class Solution { public void moveZeroes(int[] nums) { int zeronum=0; int pos=0; for(int i=0;i+zeronum<nums.length;i++){ if(nums[i]==0){ zeronum++; }else{ if(pos!=i){ nums[pos]=nums[i]; } pos++; } } for(int i=pos;i<nums.length;i++){ nums[i]=0; } }}
1 0
- Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
- 【Leet Code】283. Move Zeroes---Easy
- Leet Code OJ 172. Factorial Trailing Zeroes [Difficulty: Easy]
- Leet Code OJ 292. Nim Game [Difficulty: Easy]
- Leet Code OJ 242. Valid Anagram [Difficulty: Easy]
- Leet Code OJ 231. Power of Two [Difficulty: Easy]
- Leet Code OJ 258. Add Digits [Difficulty: Easy]
- Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]
- Leet Code OJ 217. Contains Duplicate [Difficulty: Easy]
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
- Leet Code OJ 263. Ugly Number [Difficulty: Easy]
- Leet Code OJ 100. Same Tree [Difficulty: Easy]
- Leet Code OJ 70. Climbing Stairs [Difficulty: Easy]
- Leet Code OJ 202. Happy Number [Difficulty: Easy]
- Leet Code OJ 101. Symmetric Tree [Difficulty: Easy]
- Leet Code OJ 112. Path Sum [Difficulty: Easy]
- Leet Code OJ 171. Excel Sheet Column Number [Difficulty: Easy]
- Leet Code OJ 168. Excel Sheet Column Title [Difficulty: Easy]
- 用PHP写和调用webservice最简单方法
- codeforces 585F - Digits of Number Pi (dp + acauto)
- SUSE安装、配置APR和Tomcat-Native
- iPhone设备的分辨率以及对应尺寸
- G - Closest Common Ancestors
- Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
- http响应Last-Modified和ETag以及Apache和Nginx中的配置
- html+css制作带三角的矩形
- 46. Permutations
- 算法导论排序算法汇总
- 手动导入xmpp后,再使用cocoapods的时候出现的问题
- The Swift Programming Language学习笔记(二十五)——访问控制
- 设置或修改Redis访问密码
- Mybatis代码自动生成