Given an array
Sort the array so that whenever
You may return any answer array that satisfies this condition.
A
of non-negative integers, half of the integers in A are odd, and half of the integers are even.Sort the array so that whenever
A[i]
is odd, i
is odd; and whenever A[i]
is even, i
is even.You may return any answer array that satisfies this condition.
Example 1:
Input: [4,2,5,7]
Output: [4,5,2,7]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class SortArrayByParityII {public static void main(String[] args) {int nums[] = { 4, 2, 5, 7 };nums = sortArrayByParityII(nums);System.out.println(Arrays.toString(nums));}static int[] sortArrayByParityII(int[] A) {List<Integer> v = new ArrayList<Integer>();List<Integer> v1 = new ArrayList<Integer>();int n = A.length;for (int i = 0; i < n; i++) {if (A[i] % 2 == 0)v.add(A[i]);elsev1.add(A[i]);}int l = 0, k = 0;List<Integer> res = new ArrayList<Integer>();for (int i = 0; i < n; i++) {if (i % 2 != 0)res.add(v1.get(l++));elseres.add(v.get(k++));}return res.stream().mapToInt(Integer::intValue).toArray();}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> sortArrayByParityII(vector<int> &A){vector<int> v, v1;int n = A.size();for (int i = 0; i < n; i++){if (A[i] % 2 == 0)v.push_back(A[i]);elsev1.push_back(A[i]);}int l = 0, k = 0;vector<int> res;for (int i = 0; i < n; i++){if (i & 1)res.push_back(v1[l++]);elseres.push_back(v[k++]);}return res;}int main(){vector<int> nums = {4, 2, 5, 7};nums = sortArrayByParityII(nums);cout << "[";for (int i = 0; i < nums.size() - 1; i++)cout << nums[i] << ",";cout << nums[nums.size() - 1] << "]";return 0;}
No comments:
Post a Comment