中级农民
- 积分
- 121
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-3-20
- 最后登录
- 1970-1-1
|
中间的xxxx部分如果需要保证顺序,那么需要做两次loop。第一次找出0的数量和1的数量。第二次写入。(如果需要O1空间还是有些复杂但是也能做)
如果中间的xxxx不需要保证顺序,则可以这么做:
- public void followupRearrange(int[] nums) {
- int mid = 0, right = nums.length - 1, pilot = 0;
- while (pilot <= right) {
- if (nums[pilot] == 0)
- swap(nums, mid++, pilot++);
- else if (nums[pilot] == 1)
- swap(nums, right--, pilot);
- else
- pilot++;
- }
- }
- private void swap(int[] nums, int ind1, int ind2) {
- if (ind1 == ind2)
- return;
- int temp = nums[ind1];
- nums[ind1] = nums[ind2];
- nums[ind2] = temp;
- }
复制代码
[0, 11, 0, 15, 1, 12, 1, 17, 1, 14, 0, 14, 1, 16]
成为:
[0, 0, 0, 15, 16, 12, 14, 17, 11, 14, 1, 1, 1, 1]
|
|