alicode46-最大矩形面积

 1 package solution46;
 2 import java.util.*;
 3 class Solution {
 4     public long solution(int n,long[] nums) {
 5         long  maxNum = 0;
 6         long  maxSecNum = 0;
 7         HashMap<Long,Integer> map=new HashMap<Long,Integer>();
 8         for(long i:nums){
 9             if(!map.containsKey(i)) map.put(i,1);
10             else map.put(i,map.get(i)+1);
11         }
12         for (long key : map.keySet()) {
13             if(map.get(key)>1){
14                 if(key >maxSecNum){
15                     if(key>maxNum){
16                         maxSecNum = maxNum;
17                         maxNum = key;
18                     }else{
19                         maxSecNum = key;
20                     }
21                 }
22             }
23         }
24         if(map.get(maxNum) != null && map.get(maxNum)>=4) return(maxNum*maxNum);
25         return(maxNum*maxSecNum);  
26     }
27 }

算法思路:hash。

注意12行的循环,是从hashmap的key集合中循环,每个key只循环一次。

猜你喜欢

转载自www.cnblogs.com/asenyang/p/12432469.html
今日推荐