每日算法之—数据区间划分

题目:

给定一个只包含0,1,2的数组,要求把整个数组进行区间划分,把0划分到左边,1划分到中间,2划分到右边。

如:数组为[0,1,2,1,0,1,2,2,1,0,1,2]

划分结果为:[0,0,0,1,1,1,1,1,2,2,2,2]

要求:空间复杂度为O(1),时间复杂度为O(n)。

解决思路:

假想原始数组左边有一个长度为0的0区域,右边有一个长度为0的2区域,中间是1区域,则剩下的工作就是将1区域里边的0放到0区域,2放到2区域。

首先,申明两个下标分别指向0区域和2区域,再遍历1区域,当当前数值为0时,与0区域的最右一个位置交换;如果为2则与2区域的最左边一个位置交换。注意:当与2区域交换完成后还需要检查交换过来的值是否是0,如果是则继续跟0区域交换。

public static void main(String[] args) {
		int[] nums = new int[] { 1, 1, 1, 0, 1, 2, 0, 1, 2, 0, 1, 0 };
		sort(nums);
		System.out.println(nums);
	}

	public static void sort(int[] nums) {
		int pre = -1;
		int tail = nums.length;
		int i = 0;
		while (i < tail) {
			if (nums[i] == 0) {
				pre++;
				int temp = nums[i];
				nums[i] = nums[pre];
				nums[pre] = temp;
				i++;
			} else if (nums[i] == 2) {
				tail--;
				int temp = nums[i];
				nums[i] = nums[tail];
				nums[tail] = temp;
			} else {
				i++;
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_28044241/article/details/82421506