Wednesday, August 26, 2020

LeetCode [932] Beautiful Array

 932. Beautiful Array

Medium

For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:

For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].

Given N, return any beautiful array A.  (It is guaranteed that one exists.)

 

Example 1:

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

Example 2:

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

 

Note:

  • 1 <= N <= 1000
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public int[] beautifulArray(int N) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        while(list.size()<N){
            List<Integer> tmp = new ArrayList<>();
            for(int i : list){
                if(i*2-1<=N) tmp.add(i*2-1);
            }
            for(int i : list){
                if(i*2<=N) tmp.add(i*2);
            }
            list = tmp;
        }
        return list.stream().mapToInt(i->i).toArray();
    }
}

No comments:

Post a Comment