持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情
Leetcode : leetcode-cn.com/problems/di…
GitHub : github.com/nateshao/le…
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
题目描述:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。
示例:
输入:nums = [1,2,3,4] 输出:[1,3,2,4] 注:[3,1,2,4] 也是正确的答案之一。提示:
0 <= nums.length <= 500000 <= nums[i] <= 10000
思路1:快速排序
是不是双指针的兆头?
class Solution {
public int[] exchange(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
// 奇数,放前面
while (left < right && nums[left] % 2 != 0) {
left++;
}
// 偶数,放后面
while (left < right && nums[right] % 2 == 0) {
right--;
}
if (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}
return nums;
}
}
解题思路:
考虑定义双指针 i , j分列数组左右两端,循环执行:
- 指针 i 从左向右寻找偶数;
- 指针 j 从右向左寻找奇数;
- 将 偶数 nums[i]和 奇数 nums[j] 交换。
可始终保证: 指针 i 左边都是奇数,指针 j 右边都是偶数 。
算法流程:
-
初始化: i , j 双指针,分别指向数组 nums 左右两端;
-
循环交换: 当 i = j 时跳出;
- 指针 i 遇到奇数则执行 i = i + 1 跳过,直到找到偶数;
- 指针 j 遇到偶数则执行 j = j - 1 跳过,直到找到奇数;
- 交换 nums[i] 和 nums[j] 值;
-
返回值: 返回已修改的 nums 数组。
复杂度分析:
- 时间复杂度 O(N) : N 为数组 nums长度,双指针 i, j 共同遍历整个数组。
- 空间复杂度 O(1) : 双指针 i, j 使用常数大小的额外空间。
x&1 位运算 等价于 x % 2x%2 取余运算,即皆可用于判断数字奇偶性。
package com.nateshao.sword_offer.topic_16_exchange;
import java.util.Arrays;
/**
* @date Created by 邵桐杰 on 2021/11/22 12:03
* @微信公众号 程序员千羽
* @个人网站 www.nateshao.cn
* @博客 https://nateshao.gitee.io
* @GitHub https://github.com/nateshao
* @Gitee https://gitee.com/nateshao
* Description: 调整数组顺序使奇数位于偶数前面
*/
public class Solution {
public static void main(String[] args) {
int[] nums = {2, 3, 5, 7, 7, 6, 8, 10};
int[] exchange = exchange(nums);
for (int i : exchange) {
System.out.print(i + " ");
}
System.out.println();
int[] ints = exchange2(nums);
for (int anInt : ints) {
System.out.print(anInt + " ");
}
}
public static int[] exchange(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
while (left < right && nums[left] % 2 != 0) left++;
while (left < right && nums[right] % 2 == 0) right--;
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
return nums;
}
// 位运算
public static int[] exchange2(int[] nums) {
int i = 0, j = nums.length - 1, tmp;
while (i < j) {
while (i < j && (nums[i] & 1) == 1) i++; //x&1位运算等价于 x %2取余运算,即皆可用于判断数字奇偶性。
while (i < j && (nums[j] & 1) == 0) j--;
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
return nums;
}
}
位运算击败100%
Go
package main
import "fmt"
func main() {
nums := []int{1, 2, 3, 4}
res := exchange(nums)
for _, re := range res {
fmt.Print(re)
}
}
func exchange(nums []int) []int {
left, right := 0, len(nums)-1
for left < right { //循环条件
if nums[left]%2 == 0 && nums[right]%2 != 0 { //满足则发生交换
nums[left], nums[right] = nums[right], nums[left]
}
if nums[left]%2 != 0 { //i往后走
left++
}
if nums[right]%2 == 0 { //j往前走
right--
}
}
return nums
}