示例代码1:
将length计算放在循环体外面,在leetcode运行时,结果只打败了26%的人。
public void moveZeroes(int[] nums) { int counter = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) nums[counter++] = nums[i]; } for (int j = counter; j < nums.length; j++) { nums[j] = 0; } }
示例代码2:
将length计算放在循环体外面,用一个变量size保存数组的length,在leetcode运行时,结果打败了89%的人,可见小小的一个改变,提升很大。
public void moveZeroes(int[] nums) { int size = nums.length; int counter = 0; for (int i = 0; i < size; i++) { System.out.println("i:" + i + ",counter:" + counter); if (nums[i] != 0) nums[counter++] = nums[i]; } for (int j = counter; j < size; j++) { nums[j] = 0; } }
时间: 2024-10-29 04:01:18