JAVA EASY Solution,Beat 89% no using Stack


  • 0
    J
    public class Solution {
        public int[] nextGreaterElement(int[] findNums, int[] nums) {
            if (findNums == null || nums == null || findNums.length == 0 || nums.length == 0) return new int[0];
            int len1 = findNums.length, len2 = nums.length,last;
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            if (len2 == 1) {
                map.put(nums[0], -1);
            }
            for (int i = 1; i < len2; i++) {
                if (nums[i] > nums[i-1]) {
                    map.put(nums[i-1],nums[i]);
                } else {
                    last = i;
                    while (last < len2 && nums[last] <nums[i-1]) last++;
                    if (last == len2) map.put(nums[i-1], -1);
                    else map.put(nums[i-1], nums[last]);
                }
      
            }
            if (len2 != 1) {
                map.put(nums[len2-1], -1);
            }
            
            
            int res[] = new int[len1];
            
            for (int i = 0; i < len1; i++) {
                res[i] = map.get(findNums[i]);
            }
            
            return res;
        }
    }

Log in to reply
 

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