[LeetCode] 905. Sort Array By Parity
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Example 2:
Input: nums = [0] Output: [0]
Constraints:
1 <= nums.length <= 50000 <= nums[i] <= 5000
按奇偶排序数组。
题意跟75题很类似,要求将偶数排在前,奇数排在后。思路也类似,直接给代码了。
时间O(n)
空间O(1)
Java实现
class Solution { public int[] sortArrayByParity(int[] nums) { // corner case if (nums == null || nums.length == 0) { return nums; } // normal case int left = 0; int right = nums.length - 1; int cur = 0; while (cur <= right) { if (nums[cur] % 2 == 0) { cur++; left++; } else { swap(nums, cur, right); right--; } } return nums; } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number[]} 4 */ 5 var sortArrayByParity = function (nums) { 6 // corner case 7 if (nums == null || nums.length == 0) { 8 return nums; 9 } 10 11 // normal case 12 let left = 0; 13 let right = nums.length - 1; 14 let cur = 0; 15 while (cur <= right) { 16 if (nums[cur] % 2 == 0) { 17 cur++; 18 left++; 19 } else { 20 swap(nums, cur, right); 21 right--; 22 } 23 } 24 return nums; 25 }; 26 27 var swap = function (nums, i, j) { 28 var temp = nums[i]; 29 nums[i] = nums[j]; 30 nums[j] = temp; 31 };
相关题目

浙公网安备 33010602011771号