The human voice can never reach the distance that is covered by the still small voice of conscience. 良心之声寂静微小,但它传递的距离是人声永远达不到的。 给一个整数数组,让它的奇数和偶数分开并且奇数在数组的前面,偶数在数组的后面。 这题没什么难度,首先最容易想到的是申请一个同样大小的临时数组,把原数组的值放到临时数组中,奇数从前面放,偶数从后面放,我们来看下代码 我们可以使用两个指针left和right。left从左边开始扫描,如果是奇数就往右走,如果遇到偶数就停下来(此时left指向的是偶数),right从右边开始扫描,如果是偶数就往左走,如果是奇数就停下来(此时right指向的是奇数),交换left和right指向的值。继续循环,直到left==right为止。我们就以数组[3,2,4,9,5,8,1]为例来画个图看一下问题描述
问题分析
1public int[] exchange(int[] nums) {
2 if (nums == null || nums.length == 0)
3 return nums;
4 int left = 0;
5 int right = nums.length - 1;
6 int temp[] = new int[nums.length];
7 for (int i = 0; i < nums.length; i++) {
8 if ((nums[i] & 1) == 0) {
9 //偶数从后面放
10 temp[right--] = nums[i];
11 } else {
12 //奇数从前面放
13 temp[left++] = nums[i];
14 }
15 }
16 return temp;
17}
1public static int[] exchange(int[] nums) {
2 if (nums == null || nums.length == 0)
3 return nums;
4 int left = 0;
5 int right = nums.length - 1;
6 while (left < right) {
7 //如果是奇数,就往后挪,直到遇到偶数为止
8 while (left < right && (nums[left] & 1) == 1) {
9 left++;
10 }
11 //如果是偶数,就往前挪,直到遇到奇数为止
12 while (left < right && (nums[right] & 1) == 0) {
13 right--;
14 }
15 //交换两个值
16 if (left < right) {
17 nums[left] ^= nums[right];
18 nums[right] ^= nums[left];
19 nums[left] ^= nums[right];
20 }
21 }
22 return nums;
23}
代码16到20行是交换两个数字的值,交换两个数的值有多种方式,这里选择的是通过异或来交换,如果看不明白可以看一下下面往期推荐中的第357题。
第三种方式使用的是快慢指针,和上一种解决方式有一点区别,上一种是一前一后扫描。我们这里使用的快慢指针都是从头开始扫描。我们使用两个指针,一个快指针fast,一个慢指针slow。慢指针slow存放下一个奇数应该存放的位置,快指针fast往前搜索奇数,搜索到之后然后就和slow指向的值交换,我们还以上面的数据为例画个图来分析下
1public static int[] exchange(int[] nums) {
2 int slow = 0, fast = 0;
3 while (fast < nums.length) {
4 if ((nums[fast] & 1) == 1) {//奇数
5 if (slow != fast) {
6 nums[slow] ^= nums[fast];
7 nums[fast] ^= nums[slow];
8 nums[slow] ^= nums[fast];
9 }
10 slow++;
11 }
12 fast++;
13 }
14 return nums;
15}
联系客服