Very first intuitive solution, beat 86%, using List, Greedy


  • 0
    public class Solution {
        public boolean isPossible(int[] nums) {
            if (nums == null || nums.length < 3) return false;
            List<Pair> list = new ArrayList<>();
            list.add(new Pair(nums[0]));
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] == nums[i - 1] || nums[i] == nums[i - 1] + 1) {
                    insertList(list, nums[i]);
                } else {
                    if (!checkList(list)) return false;
                    list.add(new Pair(nums[i]));
                }
            }
            return checkList(list);
        }
        
        private boolean checkList(List<Pair> list) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).end - list.get(i).start < 2) return false;
            }
            list.clear();
            return true;
        }
        
        private void insertList(List<Pair> list, int n) {
            for (int i = list.size() - 1; i >= 0 ; i--) {
                if (list.get(i).end == n - 1) {
                    list.get(i).end = n;
                    return;
                }
            }
            list.add(new Pair(n));
        }
        
        public class Pair {
            int start;
            int end;
            public Pair(int val) {
                start = val;
                end = val;
            }
        }
    }
    

Log in to reply
 

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