zoukankan      html  css  js  c++  java
  • [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 题目总结

  • 相关阅读:
    JAVA的中文字符乱码问题
    JAVA SSH 框架介绍
    MySQL必备命令
    java文件操作
    注意事项
    再探java基础——throw与throws
    table与div互相嵌套注意
    数列F[19] + F[13]的值
    统计各类字符个数
    长理ACM 14-星期几(谌海军)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13097223.html
Copyright © 2011-2022 走看看