Beautiful Arrangement II


  • 0

    Click here to see the full article post


  • 0
    G

    Great answer, I like the Approach #2


  • 0
    B

    C++ Vesion

    class Solution {
    public:
    vector<int> constructArray(int vN, int vK) {
    vector<int> Result;
    for (unsigned int i = 1; i <= (vK + 1) / 2; ++i)
    {
    Result.push_back(i);
    Result.push_back(vK - i + 2);
    }

    	if (vK % 2 == 0)
    	{
    		Result.push_back(Result[Result.size() - 1] - 1);
    	}
    
    	for (unsigned int i = vK + 2; i <= vN; ++i)
    	{
    		Result.push_back(i);
    	}
    
    	return Result;
    }
    

    };


  • 0
    L

    Here is my accepted solution:

    class Solution {
    public int[] constructArray(int n, int k) {
    int[] X=new int[n];
    X[0]=1;
    for(int i=1;i<=k;i++){
    if(i%2==1)
    X[i]=X[i-1]+(k-i+1);
    else
    X[i]=X[i-1]-(k-i+1);
    }
    for(int i=k+1;i<n;i++)
    X[i]=i+1;
    return X;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.