(Leetcode)sort-array by parity-ii,Javaプール

8424 ワード

  • 題:https://leetcode.com/problems/sort-array-by-parity-ii/submissions/2
  • public int[] sortArrayByParityII(int[] nums) {
            int size = 0;
            if (nums.length % 2 == 0) {
                size = nums.length / 2;
            } else {
                size = nums.length / 2 + 1;
            }
            //int[] odd = new int[size];
            //int[] evn = new int[size];
            List<Integer> odd = new ArrayList<>();
            List<Integer> evn = new ArrayList<>();
    
            int eIdx = 0, oIdx = 0;
            for (int i : nums) {
                if (i % 2 == 0) {
                    //evn[eIdx++] = i;
                    evn.add(i);
                } else {
                    //odd[oIdx++] = i;
                    odd.add(i);
                }
            }
    
    
            Collections.sort(odd, Collections.reverseOrder());
            Collections.sort(evn, Collections.reverseOrder());
    
            int[] answer = new int[nums.length];
    
            for (int i = 0; i < nums.length; i++) {
                if (i % 2 == 0) {
                    answer[i] = evn.get(i / 2);
                } else {
                    answer[i] = odd.get(i / 2);
                }
    
            }
            return answer;
        }