Beautiful array solution

Nice array: Given a length of the array ARR of N, the array of integers from 1 to N to the composition and satisfy arr [k] * 2 is not equal to arr [i] + arr [j] (i <k <j)

 

E.g:

4 array of length: {2,1,4,3} 

An array of length 8: [1,5,3,7,2,6,4,8]

 

Suppose a beautiful array is an array, the array must meet the following conditions:

Every number (1) in the array plus an arbitrary integer, still maintain a beautiful array.

For example: {2,1,4,3} will add a whole

{3,2,5,4} still obtain satisfying

 

(2) Each number in the array are multiplied by a non-zero integer, still satisfied

For example: {2,1,4,3} will be multiplied by 2

{4,2,8,6} to give

 

(3) The most important one came, would be a pretty full array of odd and a full array of pretty even number of merged together, it's still a pretty array.

For example: {2,1,4,3} will be multiplied by 2

Pretty obtain the even array {4,2,8,6}

This array then all the even-1, to give the odd array {3,1,7,5}

These two arrays combined to give {3,1,7,5,4,2,8,6} still satisfy the rule.

So by this rule, you get a length of 4,8,16,32 .... beautiful array

 

(4) The last rule is a beautiful array by deleting a number, still able to maintain a beautiful array

 

code show as below:

class Solution {
    public int[] beautifulArray(int N) {
        int array[] = new int[2000];
        int array2[] = new int[N];
        int k  =0;
        array[0] = 2;
        array[1] = 1;
        array[2] = 4;
        array[3] = 3;
        for(int i = 1;i<200;i*=2){
            for(int j = 0;j<i*4;j++){
                array[i*4+j] = array[j]*2;
                array[j] = array[j]*2-1;
            }
        }
        
        for(int i = 0;i<2000;i++){
            if(k<N&&array[i]!=0&&array[i]<=N){
               
                array2[k] = array[i];
                k++;
            }
                
        }
        
        return array2;
    }
}

 

Guess you like

Origin www.cnblogs.com/yyywh/p/11619817.html