给你一个整数数组 nums
,将 nums
中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。
返回满足此条件的 任一数组 作为答案。
示例 1:
输入:nums = [3,1,2,4] 输出:[2,4,3,1] 解释:[4,2,3,1]、[2,4,1,3] 和 [4,2,1,3] 也会被视作正确答案。
示例 2:
输入:nums = [0] 输出:[0]
我的思路:很单纯,就用两个数组一个装奇数,一个装偶数,再合并到一个数组
class Solution {
public int[] sortArrayByParity(int[] nums) {
int arr1[]=new int[nums.length];
int arr2[]=new int[nums.length];
int p=0;
int q=0;
for(int x:nums) {
if (x % 2 == 0) {
arr1[p++] = x;
} else {
arr2[q++] = x;
}
}
int m=0;
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<p;i++){
list.add(m,arr1[i]);
m++;
}
for(int i=0;i<q;i++){
list.add(m,arr2[i]);
m++;
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
看看大佬的:
方法一:两次遍历
新建一个数组 res 用来保存排序完毕的数组。遍历两次 nums,第一次遍历时把所有偶数依次追加到 res 中,第二次遍历时把所有奇数依次追加到 res 中。
class Solution {
public int[] sortArrayByParity(int[] nums) {
int n = nums.length, index = 0;
int[] res = new int[n];
for (int num : nums) {
if (num % 2 == 0) {
res[index++] = num;
}
}
for (int num : nums) {
if (num % 2 == 1) {
res[index++] = num;
}
}
return res;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/sort-array-by-parity/solutions/1449791/an-qi-ou-pai-xu-shu-zu-by-leetcode-solut-gpmm/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
同样是两次遍历,我的就很好的演绎了什么叫脱裤子放屁(*_*)
方法二:双指针+一次遍历
class Solution {
public int[] sortArrayByParity(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int left = 0, right = n - 1;
for (int num : nums) {
if (num % 2 == 0) {
res[left++] = num;
} else {
res[right--] = num;
}
}
return res;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/sort-array-by-parity/solutions/1449791/an-qi-ou-pai-xu-shu-zu-by-leetcode-solut-gpmm/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
简直完美!鼓掌!