输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。
示例:
输入:nums = [1,2,3,4] 输出:[1,3,2,4] 注:[3,1,2,4] 也是正确的答案之一。
提示:
0 <= nums.length <= 50000
0 <= nums[i] <= 10000
方法一:双指针
我们定义两个指针
接下来,我们从左到右遍历数组,当
时间复杂度
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
j = 0
for i, x in enumerate(nums):
if x & 1:
nums[i], nums[j] = nums[j], nums[i]
j += 1
return nums
class Solution {
public int[] exchange(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] % 2 == 1) {
int t = nums[i];
nums[i] = nums[j];
nums[j++] = t;
}
}
return nums;
}
}
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int j = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] & 1) {
swap(nums[i], nums[j++]);
}
}
return nums;
}
};
func exchange(nums []int) []int {
j := 0
for i, x := range nums {
if x&1 == 1 {
nums[i], nums[j] = nums[j], nums[i]
j++
}
}
return nums
}
/**
* @param {number[]} nums
* @return {number[]}
*/
var exchange = function (nums) {
let j = 0;
for (let i = 0; i < nums.length; ++i) {
if (nums[i] & 1) {
const t = nums[i];
nums[i] = nums[j];
nums[j++] = t;
}
}
return nums;
};
function exchange(nums: number[]): number[] {
let j = 0;
for (let i = 0; i < nums.length; ++i) {
if (nums[i] & 1) {
const t = nums[i];
nums[i] = nums[j];
nums[j++] = t;
}
}
return nums;
}
impl Solution {
pub fn exchange(mut nums: Vec<i32>) -> Vec<i32> {
let mut j = 0;
for i in 0..nums.len() {
if nums[i] % 2 == 1 {
nums.swap(i, j);
j += 1;
}
}
nums
}
}
public class Solution {
public int[] Exchange(int[] nums) {
int j = 0;
for (int i = 0; i < nums.Length; ++i) {
if (nums[i] % 2 == 1) {
int t = nums[i];
nums[i] = nums[j];
nums[j++] = t;
}
}
return nums;
}
}