[Leetcode]Move Zeroes
来源:互联网 发布:绿茶软件园php源码 编辑:程序博客网 时间:2024/04/30 08:18
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:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
方法一:时间复杂度O(N^2)
public class Solution { public void moveZeroes(int[] nums) { if (nums == null || nums.length == 1) { return; } int zeroCount = 0; int zeroSequenceLength = 0; for (int i = 0; i < nums.length - zeroCount; i++) { if (0 == nums[i]) { ++zeroSequenceLength; } else { if (zeroSequenceLength >= 1) { for (int j = i; j < nums.length - zeroCount; j++) { nums[j - zeroSequenceLength] = nums[j]; } zeroCount += zeroSequenceLength; i = i - zeroSequenceLength; zeroSequenceLength = 0; } } } for (int k = nums.length - 1; k > nums.length - 1 - zeroCount; k--) { nums[k] = 0; } }}
方法二:时间复杂度O(N)
public class Solution { public void moveZeroes(int[] nums) { int newIndex = 0; for (int i = 0; i < nums.length ; i++) { if (nums[i] != 0) { nums[newIndex++] = nums[i]; } } for (; newIndex < nums.length; newIndex++) { nums[newIndex] = 0; } }}
1 0
- leetcode 283: Move Zeroes
- leetcode - Move Zeroes
- Leetcode: Move Zeroes
- LeetCode - Move Zeroes
- LeetCode-Move Zeroes
- [LeetCode]Move Zeroes
- leetcode-283-Move Zeroes
- [leetcode 283]Move Zeroes
- LeetCode---Move Zeroes
- LeetCode 283----Move Zeroes
- LeetCode Move Zeroes
- LeetCode Move Zeroes
- Leetcode #283 Move Zeroes
- leetcode: (283) Move Zeroes
- [LeetCode 283] Move Zeroes
- 【LeetCode】Move Zeroes
- LeetCode-Move Zeroes
- [LeetCode] Move Zeroes
- Centos下安装zookeeper集群
- Android 项目(详解一)之—— 基础类BaseActivity/BaseFragment/总的Application
- 在SQL中,有各种各样的日期时间格式,保存一份 Convert Date
- 软件功能测试
- java 向量
- [Leetcode]Move Zeroes
- InternetDVB
- AndroidValidator使用
- extern "c" __declspec(dllimport) __declspec(dllexport)
- IOS中NSPredicate的用法
- python实现ftp上下传,支持断点续传。
- 10.10笔记,android通知栏兼容性,matches the given name 'android:Widget.Material.Button.Colored'.
- JQuery控制只输入数字,关闭输入法
- QQ飞车