题目链接
283.移动零
代码
最终是这个样子的
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public void moveZeroes(int[] nums) {
int notZeroIndex = -1;
for (int i = 0; i < nums.length; i++) { if (nums[i] != 0 && i != ++notZeroIndex) { nums[notZeroIndex] = nums[i]; nums[i] = 0; } } } }
|
再看是怎样一步一步过来的
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
| class Solution { public void moveZeroes(int[] nums) { int notZeroIndex = -1;
for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { ++notZeroIndex;
if (i == notZeroIndex) { } else { nums[notZeroIndex] = nums[i]; nums[i] = 0; } } } } }
|
简化,去掉 i == notZeroIndex 的空 if 语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public void moveZeroes(int[] nums) { int notZeroIndex = -1;
for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { ++notZeroIndex;
if (i != notZeroIndex) { nums[notZeroIndex] = nums[i]; nums[i] = 0; } } } } }
|
++ 可以放到判断条件里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public void moveZeroes(int[] nums) { int notZeroIndex = -1;
for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { if (i != ++notZeroIndex) { nums[notZeroIndex] = nums[i]; nums[i] = 0; } } } } }
|
短路与,if 条件合并
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public void moveZeroes(int[] nums) { int notZeroIndex = -1;
for (int i = 0; i < nums.length; i++) { if (nums[i] != 0 && i != ++notZeroIndex) {
nums[notZeroIndex] = nums[i]; nums[i] = 0; } } } }
|
复杂度分析