My Java Solution


  • 0
    C
    public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
       
        if(m == 0)
        {
        	for(int i=0;i<nums2.length;i++)
        	{
        		nums1[i] = nums2[i];
        	}
            return ;
        }
        else if(n == 0)
        {
            return ;
        }
        
     //define two pointers for each arrays
    	int p1=0,p2 =0;
    	for(int i=0;i<m;i++)
    	{   //compare those two arrays
    		if(nums1[p1] <= nums2[p2])
    		{
    			p1++;
    		}
    		else
    		{	int tmp = nums2[p2];
    			nums2[p2] = nums1[p1];
    			nums1[p1] =tmp;
    			p1++;
    			//swap(nums1[p1],nums2[p2]);
    			quicksort(nums2,0,n-1);
    		}
    	}
    	for(int i=m;i<(m+n);i++)
    	{
    		nums1[i] = nums2[p2++];
    	}
    	return ;
    }
    
    public void quicksort(int[] nums, int p, int r)
    {
    	if(p<r)
    	{
    		int q = partition(nums,p,r);
    		quicksort(nums,0,q-1);
    		quicksort(nums,q+1,r);
    	}
    	
    }
    
    public int partition(int[] nums, int p, int r) {
    	
    	int k=p-1;
    	for(int i=p;i<r;i++)
    	{
    		if(nums[i] <= nums[r])
    		{	int tmp = nums[i];
    			nums[i] = nums[++k];
    			nums[k] = tmp;
    		}
    	}
    	
    	int tmp = nums[r];
    	nums[r] = nums[++k];
    	nums[k] = tmp;
    	/*swap(nums[++k],nums[r]);*/
    	
    	return k;
    }
    }

Log in to reply
 

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