Java 4ms Solution


  • 0
    Q
    	public int nextGreaterElement(int n) {
    		String num = n+"";
    		char[] chars = num.toCharArray();
    		for (int i = chars.length-1; i >= 0; i--) {
    			if(i==0) return -1;
    			if(i-1>=0 && chars[i-1]<chars[i]){
    				int temp = chars[--i];
    				for (int j = chars.length-1; j > i; j--) {
    					if(chars[j]>temp){
    						int t = chars[i];
    						chars[i] = chars[j];
    						chars[j] = (char) t;
    						int k = chars.length-1;
    						i++;
    						while(i<k){
    							t = chars[i];
    							chars[i] = chars[k];
    							chars[k] = (char) t;
    							k--;
    							i++;
    						}
    						Long tt = Long.parseLong(new String(chars));
    						if(tt>Integer.MAX_VALUE) return -1;
    						return Integer.parseInt(tt+"");
    					}
    				}
    			}
    		}
    		
    		return -1;
    
    	}
    

Log in to reply
 

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