LeetCode--Sort Array By Parity & N-Repeated Element in Size 2N Array (Easy)

905. Sort Array By Parity (Easy)

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
 
Note:

1 <= A.length <= 5000
0 <= A[i] <= 5000

solution

我的解法

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int i = 0, j = A.length - 1; int temp;
        while (i < j)
        {
            if (A[i] % 2 != 0)
            {
                while (A[j] % 2 != 0 & i < j)
                    j--;
                if (i < j)
                {
                    temp = A[i];
                    A[i] = A[j];
                    A[j] = temp;
                    j--;
                }
            }
            i++;
        }
        return A;
    }
}

大佬的解法

    public int[] sortArrayByParity(int[] A) {
        for (int i = 0, j = 0; j < A.length; j++)
            if (A[j] % 2 == 0) {
                int tmp = A[i];
                A[i++] = A[j];
                A[j] = tmp;;
            }
        return A;
    }

reference
https://leetcode.com/problems/sort-array-by-parity/discuss/170734/C%2B%2BJava-In-Place-Swap

总结

此题主要考察数组相关的知识点。我的思路借鉴了快速排序的思想。首先设置两个计数器i与j分别记录数组的开头下标和结尾下标,然后用一个while循环从数组左端开始遍历数组,如果A[i]为奇数,则用一个while循环从数组右端开始遍历数组,直到A[j]为偶数(注意i<j)则跳出循环。假如此时j处的元素为偶数,如果i<j,就交换A[i]和A[j],并将j++,否则什么都不做。最后,当外层循环结束后,将A返回。
大佬的解法是将数组中的偶数与前面的奇数交换,即当遍历数组时,遇到奇数就跳过,遇到偶数就与前面的奇数相交换。
Notes:
1.此类数组问题最好只用题目给定的数组解决问题,如无必要,不要用额外的数组来存储中间结果。比如此题,如果新建一个int数组来存储结果,虽然也可以做出来,但是就失去了题目想要考察的技巧了。

961. N-Repeated Element in Size 2N Array (Easy)

In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.

Return the element repeated N times.

Example 1:

Input: [1,2,3,3]
Output: 3

Example 2:

Input: [2,1,2,5,3,2]
Output: 2

Example 3:

Input: [5,1,5,2,5,3,5,4]
Output: 5

Note:

4 <= A.length <= 10000
0 <= A[i] < 10000
A.length is even

solution

猜你喜欢

转载自www.cnblogs.com/victorxiao/p/11104763.html