share my java solution, O(n) time complexity!


  • 0
    T

    Basic idea, suppose we have 1,2,3...n, we need to transform it into like this:
    1,n,2,n-1,3,n-2,...........

    class Solution {
        public int[] constructArray(int n, int k) {
            int[] nums = new int[n];
            int count = 1;
            int lower = 1;
            int higher = n;
            
            int cnt = 0;
            while(k--!=0){
              if(cnt%2==0){
                  nums[cnt]=lower;
                  lower++;
              }else{
                  nums[cnt]=higher;
                  higher--;
              }
              cnt++;
            }
            
            if(cnt%2==1){
                while(cnt<n){
                    nums[cnt++]=lower++;
                }
            }else{
                while(cnt<n){
                    nums[cnt++]=higher--;
                }
            }
            
            return nums;
        }
    }
    
    

Log in to reply
 

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