LeetCode 496 - Next Greater Element I

quesion:

在这里插入图片描述

Analysis:

Two methods:

  1. brute force:
  • find the poistion of each element of nums1 in nums2
  • search nums2 until find, or set as -1
  • time complexity O(nm), space O(m)
  1. stack ,hashmap
  • fInd each NEXT GREATER of nums2 by using stack, and then store the result in HashMap
    – while stack is not empty, pop until stack.peek() >nums2[]
    – if stack is empty , put -1 in the HashMap
    – if stack is not empty and peek() >nums2[
    ], put nums2[*] into hashmap
  • extract the NEXT GREATER for nums1 from HashMap

Code

class solution1{
	 public int[] nextGreaterElement(int[] nums1, int[] nums2) {
	
			int[] res = new int[nums1.length];
			Arrays.fill(res, -1);
			
			for (int i=0; i<nums1.length; i++) {
				for (int j=findIndex(nums2, nums1[i])+1; j<nums2.length; j++) {
					if (nums2[j] > nums1[i]){
	                    res[i] = nums2[j];
	                    break;
	                } 
				}				
			}					
			return res;
		}
		
		// this function will return the position of key in nums
		public int findIndex(int[] nums, int key) {
			int res = -1;
			for (int i=0; i<nums.length; i++) {
				if (nums[i] == key) {
					res = i;
				}
			}		
			return res;
		}
		
		public int[] nextGreaterElement1(int[] nums1, int[] nums2) {
			int[] res = new int[nums1.length];
			Arrays.fill(res, -1);
			
			for (int i=0; i< nums1.length; i++) {
				boolean found = false;
				int j = 0;
				for (; j<nums2.length; j++) {
					if (nums2[j] == nums1[i]) {
						found = true;
					}
					
					if (found && nums2[j] > nums1[i] ) {
						res[i] = nums2[j];
						break;
					}
					
					if (j == nums2.length) {
						res[i] = -1;
					}	
				}		
			}
			return res;
		}
		
		
		 public int[] nextGreaterElement2(int[] nums1, int[] nums2) {
			 
			 int[] res = new int[nums1.length];
			 HashMap<Integer, Integer> map = new HashMap<>();
			 Stack<Integer> stack = new Stack<>();
			 
			 for (int j=nums2.length-1; j>=0; j--) {
				 
				 
				 while(!stack.isEmpty() && nums2[j] > stack.peek()) {
					 stack.pop();
				 }
				 
				 if (stack.isEmpty()) {
					 map.put(nums2[j], -1);
				 }else {
					 map.put(nums2[j], stack.peek());
				 }
			 
				 stack.push(nums2[j]);	 
				 }	 
			 
			 for (int i=0; i<nums1.length; i++) {
				 res[i] = map.get(nums1[i]);
			 } 
			 return res;	 
		 }
		
		
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值