C solution O(n) runtime , O(n) space, 3ms


  • 0
    S
    int nextGreaterElement(int n) {
    	int pre=-1, cur=-1, p, b=0, i=0, j;
    	int* nums;
    	if(n < 10)	return -1;
    	p=n;
    	while(p > 0)
    	{
    		b ++;
    		p /= 10;
    	}
    	nums = malloc(sizeof(int) * b);
    	p = n;
    
    	while(p > 0)
    	{
    		cur = p % 10;
    		p = p / 10;
    		nums[i++] = cur;
    		if(pre > cur)
    		{
    			for(j=0; j < i; j++)
    			{
    				if(nums[j] > cur){
    					nums[i-1] = nums[j];
    					nums[j] = cur;
    					break;
    				}
    			}
    			p = p * 10 + nums[i-1];
    			for(j=0; j<i-1; j++)
    			{
    				if(j==i-2 && (p>214748364 || (p==214748364 && nums[j] > 7)))	return -1;
    				p = p*10 + nums[j];
    			}
    			return p;
    		}
    		pre = cur;
    	}
    
    	free(nums);
    	return -1;
    }
    
    

Log in to reply
 

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