The most straightforward C solution I could come up with.


  • 0
    T
    void rotate(int* nums, int numsSize, int k) {
        
        int arr[numsSize*2];
        
        for(int i=0; i<numsSize; i++){
            arr[i] = nums[i];
            arr[i+numsSize] = nums[i];
        }
        
        int start = numsSize - k % numsSize;
        
        for(int j=0; j<numsSize; j++) nums[j] = arr[j+start];
        
    }

  • 1

    void rotate(vector<int>& nums, int k)
    {
    int step = (k % nums.size());
    if (step == 0)
    return;

    int l = 0;
    int r = nums.size() - 1;
    int mid = r - step + 1;
    int ls = 0;
    int rs = 0;
    int tmp = 0;
    
    while (l < mid && r >= mid)
    {
    	ls = mid - l;
    	rs = r - mid + 1 ;
    	
    	if (ls < rs)
    	{
    		for (int i = 0; i < ls; ++i)
    		{
    			tmp = nums[l];
    			nums[l] = nums[mid];
    			nums[mid] = tmp;
    
    			++l;
    			++mid;
    		}
    	}
    	else
    	{
    		for (int i = 0; i < rs; ++i)
    		{
    			tmp = nums[r];
    			nums[r] = nums[mid - 1];
    			nums[mid - 1] = tmp;
    
    			--r;
    			--mid;
    		}
    	}
    }
    

    }


Log in to reply
 

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