Simple Java Solution


  • 0
    R
    public class Solution {
        public int nextGreaterElement(int n) {
            List<Integer> list = getList(n);
            int N = list.size(), i = N - 2;
            if(N == 1) return -1;
            while(i >= 0 && list.get(i) >= list.get(i + 1)) i--;
            if(i == -1) return -1;
            int j = N - 1, k = -1;
            while(j > i) {
                if(list.get(j) > list.get(i) && (k == -1 || list.get(k) > list.get(j))) k = j;
                j--;
            }
            
            swap(list, i, k);
            Collections.sort(list.subList(i + 1, N));
            long next = getNum(list);
            if(next > Integer.MAX_VALUE) return -1;
            return (int)next;
        }
        
        private long getNum(List<Integer> list) {
            long sum = 0;
            for(int num : list) sum = sum * 10 + num;
            return sum;
        }
        
        private void swap(List<Integer> list, int x, int y) {
            int temp = list.get(x);
            list.set(x, list.get(y));
            list.set(y, temp);
        }
        
        private List<Integer> getList(int n) {
            List<Integer> result = new ArrayList<>();
            while(n != 0) {
                result.add(0, n%10);
                n /= 10;
            }
            return result;
        }
    }
    
    

Log in to reply
 

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