Move Zeroes
来源:互联网 发布:投诉数据分析ppt 编辑:程序博客网 时间:2024/06/05 16:07
题目地址:https://leetcode.com/problems/move-zeroes/
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.
这个题目有点意思,就是把0都放在后面,把非零的数字放在前面。
要是不保证非零元素的顺序,那就容易多了,直接交换即可,但是人家题目要求保持原序。
另外如果按照顺序表去处理(其实也就是顺序表),每移除一个0,后面的元素就往迁移,那这个移动次数无疑也很多,所以得想办法尽量少做移动的操作。
我们可以这么做:
找两根指针p和q,p指向每次迭代的第一个0的位置,q指向每次迭代的第一个非0的位置。每次就交换这两个位置的元素就可以了,准确滴说不算交换,还是移动。
代码实现如下:
public class MoveZeroes { public void moveZeroes(int[] nums) { if (nums.length < 2) return; int p = 0; int q = 0; while (p < nums.length && nums[p] != 0) p++; q = p; while (q < nums.length && nums[q] == 0) q++; while (q < nums.length) { nums[p] = nums[q]; nums[q] = 0; while (p < nums.length && nums[p] != 0) p++; while (q < nums.length && nums[q] == 0) q++; } } public static void main(String[] args) { MoveZeroes zeroes = new MoveZeroes(); int[] nums = {0,0}; zeroes.moveZeroes(nums); for (int i = 0; i < nums.length; i++) System.out.println(nums[i]); }}
这个代码的时间复杂度是:O(n)
0 0
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- 基于visual c++之windows核心编程代码分析(11)实现屏幕截取
- 评价特征 分类
- 关于Fragment中的getActivity()返回null导致程序崩溃的解决方案
- python标准库之logging
- 多线程之Handler详解
- Move Zeroes
- C语言函数的声明以及函数原型
- 基于visual c++之windows核心编程代码分析(12)使用信号量同步线程
- 28335与AD7606后续
- 基于visual c++之windows核心编程代码分析(14)使用Event同步线程
- 常见对象_DateFormat实现日期和字符串的相互转换
- WebService的java原生开发
- php超全局数组
- 基于visual c++之windows核心编程代码分析(15)使用Mutex同步线程