• [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 <= 5000
    • 0 <= 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 };

    相关题目

    75. Sort Colors

    905. Sort Array By Parity

    922. Sort Array By Parity II

    LeetCode 题目总结

  • 相关阅读:
    G-sensor驱动分析
    写i2c_client驱动的两种方式
    TP分析
    JAVA基础知识要点
    springboot-线程池简单使用
    java 实现好看的图形验证码
    正则表达式校验15/18位生份证-JAVA版
    springboot2.X集成HttpClient 发送HTTPS 请求
    linux-修改时区时间
    springboot2.X 在项目启动后执行一段自定义代码
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13097223.html
Copyright © 2020-2023  润新知