forked from liuyubobobo/Play-with-Algorithm-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
36 lines (27 loc) · 1.03 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.*;
// 283. Move Zeroes
// https://leetcode.com/problems/move-zeroes/description/
// 时间复杂度: O(n)
// 空间复杂度: O(n)
class Solution {
public void moveZeroes(int[] nums) {
ArrayList<Integer> nonZeroElements = new ArrayList<Integer>();
// 将vec中所有非0元素放入nonZeroElements中
for(int i = 0 ; i < nums.length ; i ++)
if(nums[i] != 0)
nonZeroElements.add(nums[i]);
// 将nonZeroElements中的所有元素依次放入到nums开始的位置
for(int i = 0 ; i < nonZeroElements.size() ; i ++)
nums[i] = nonZeroElements.get(i);
// 将nums剩余的位置放置为0
for(int i = nonZeroElements.size() ; i < nums.length ; i ++)
nums[i] = 0;
}
public static void main(String args[]){
int[] arr = {0, 1, 0, 3, 12};
(new Solution()).moveZeroes(arr);
for(int i = 0 ; i < arr.length ; i ++)
System.out.print(arr[i] + " ");
System.out.println();
}
}