Leetcode(算法) 905. 按奇偶排序数组


给你一个整数数组 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]

提示:

1 <= nums.length <= 5000
0 <= nums[i] <= 5000
通过次数74,796提交次数105,

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-array-by-parity
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


简简单单双指针

在这里插入图片描述

class Solution {
    
    
    public int[] sortArrayByParity(int[] nums) {
    
    
        int l=0,r=nums.length-1;
        while(l<r){
    
    
            while(l<r && nums[l]%2==0){
    
    
                ++l;
            }
            while(r>-1 && nums[r]%2==1){
    
    
                --r;
            }

            if(l<r && nums[l]%2==1 && nums[r]%2==0){
    
    
                int num=nums[l];
                nums[l]=nums[r];
                nums[r]=num;

            }
        }
        return nums;
    }
}

新建数组,从头遍历旧数组偶数放子女数组头奇数放新数组尾

猜你喜欢

转载自blog.csdn.net/qq_44627608/article/details/124467099