赞
踩
题目描述:
给定一个一维数组,将其中为0的元素删除掉,非零元素的相对位置保持不变,最终目标数组保留在原数组中,并且目标数组长度之外的元素全部置为0。
解题思路:
(1)数组非零元素往前移动,时间复杂度O(n)。
思路:先将非0的元素往前靠,最后再将剩下的位置重置为0。
实现代码:
- public void moveZeroes(int[] nums) {
- if(nums.length < 1)
- return ;
- int Index = 0;
- for (int i=0; i<nums.length; i++){
- if(0 != nums[i]){
- nums[Index++] = nums[i];
- }
- }
- for(int i=Index; i<nums.length; i++){
- nums[i] = 0;
- }
-
- }
(2)利用两个指针,交换位置。时间复杂度O(n)。
思路:可以用两个指针,第一个指针永远指向从左往右为0的元素,第二个指针为遍历指针,当遍历指针指向的值为非0的时候,将这个元素与第一个指针指向的元素交换。
- public void moveZeroes(int[] nums) {
- //first指针永远指向当前为0的元素
- int first = 0;
-
- for (int second = 0; second < nums.length; second++) {
- //为0的和非0的交换
- if (nums[second] != 0) {
- int temp = nums[first];
- nums[first] = nums[second];
- nums[second] = temp;
- first++;
- }
- }
- }
Reference:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。