Easy to understand Java solution


  • 0

    /*
    Iterate from end to start. Switch when first found the smallest element in the tail part and then swap. Concat these chars to a strign and convert to a number.
    Otherwise, return -1.
    */

    public int nextGreaterElement(int n) {
            if(n<10) return -1;
            char[] num = Integer.valueOf(n).toString().toCharArray();
            int i = num.length-1;
            
            do{
            	char[] tail = Arrays.copyOfRange(num, i, num.length);
            	Arrays.sort(tail);
            	for(int j=0;j<tail.length;j++){
            		if(tail[j]>num[i-1]) {
            			char swap = tail[j];
            			tail[j]=num[i-1];
            			num[i-1] = swap;
            			
            			String head = new String(Arrays.copyOf(num, i));
            			String nextGreater = head + new String(tail);
            			try{
            				return Integer.parseInt(nextGreater);
            			}catch (Exception ex){
            				return -1;
            			}
            		}
            	}
            }while(--i>0);
            
            return -1;
        }
    }

Log in to reply
 

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