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

My 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;
    }
}

Gangster solution

    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

to sum up

This problem mainly on an array of relevant knowledge. I borrowed the idea of the sort of quick thinking. First set the two counters i and j are recorded at the beginning and end of the subscript of an array subscript, then a loop from the array while the left traversing the array, if A [i] is odd, the while loop from the array with a right traversing array, until the A [j] is an even number (note that i <j) is out of the loop. If the element j at this time is an even number, if i <j, exchanged A [i] and A [j], and j ++, or do nothing. Finally, when the end of the outer loop, the A returns.
The solution is to big brother foregoing even and odd array exchange, i.e. when traversing the array, the odd-skipped encountered encountered previously exchanged on the even odd.
Notes:
1. Such an array of issues are best used only title given array to solve the problem, if not necessary, do not use an additional array to store intermediate results. So the question than if a new int array to store the results, although you can also do it, but lost the skills of the subject you want to study.

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

Guess you like

Origin www.cnblogs.com/victorxiao/p/11104763.html