forked from liuyubobobo/Play-with-Algorithm-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution3.java
36 lines (29 loc) · 945 Bytes
/
Solution3.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
// 283. Move Zeroes
// https://leetcode.com/problems/move-zeroes/description/
//
// 原地(in place)解决该问题
// 时间复杂度: O(n)
// 空间复杂度: O(1)
class Solution3 {
public void moveZeroes(int[] nums) {
int k = 0; // nums中, [0...k)的元素均为非0元素
// 遍历到第i个元素后,保证[0...i]中所有非0元素
// 都按照顺序排列在[0...k)中
// 同时, [k...i] 为 0
for(int i = 0 ; i < nums.length ; i ++)
if(nums[i] != 0)
swap(nums, k++, i);
}
private void swap(int[] nums, int i, int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void main(String args[]){
int[] arr = {0, 1, 0, 3, 12};
(new Solution3()).moveZeroes(arr);
for(int i = 0 ; i < arr.length ; i ++)
System.out.print(arr[i] + " ");
System.out.println();
}
}