Leetcode Weekly Contest 259(数组、哈希)

题目链接: Leetcode Weekly Contest 259

1、2011. Final Value of Variable After Performing Operations

难度:Easy

代码:

class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int res=0;
        for(String s:operations){
            if(s.equals("X++")||s.equals("++X")){
                res++;
            }
            else{
                res--;
            }
        }
        return res;
    }
}

2、2012. Sum of Beauty in the Array

难度:Medium

class Solution {
    public int sumOfBeauties(int[] nums) {
        int n=nums.length;
        int[] prevMax=new int[n];
        int max=0;
        for(int i=0;i<n;i++){
            max=Math.max(max,nums[i]);
            prevMax[i]=max;//prevMax[i]表示nums[0,i]的最大值
        }
        int[] latterMin=new int[n];
        int min=Integer.MAX_VALUE;
        for(int i=n-1;i>=0;i--){
            min=Math.min(min,nums[i]);
            latterMin[i]=min;//prevMax[i]表示nums[i,n-1]的最小值
        }
        int res=0;
        for(int i=1;i<=n-2;i++){
            if(nums[i]>prevMax[i-1]&&nums[i]<latterMin[i+1]){
                res+=2;
            }
            else if(nums[i]>nums[i-1]&&nums[i]<nums[i+1]){
                res+=1;
            }
            else{
                res+=0;
            }
        }
        return res;
    }
}

3、2013. Detect Squares

难度:Medium

思路:

将点的坐标进行哈希映射进行存储,校验对角顶点来判断是否能构成正方形。

代码

class DetectSquares {
    Map<Integer,Integer> map;
    int mod=2000;
    public DetectSquares() {
        map=new HashMap<>();
    }
    
    public void add(int[] point) {
        int val=point[0]*mod+point[1];
        map.put(val,map.getOrDefault(val,0)+1);
    }
    
    public int count(int[] point) {
        int res=0;
        int x=point[0],y=point[1];
        for(int p:map.keySet()){//枚举对角点
            int xx=p/mod;
            int yy=p%mod;
            int a=Math.abs(x-xx);
            int b=Math.abs(y-yy);
            if(a!=b||a==0||b==0){
                continue;
            }
            int p1=x*mod+yy;
            int p2=xx*mod+y;
            if(map.containsKey(p1)&&map.containsKey(p2)){
                res+=map.get(p)*map.get(p1)*map.get(p2);
            }
        }
        return res;
    }
}

/**
 * Your DetectSquares object will be instantiated and called as such:
 * DetectSquares obj = new DetectSquares();
 * obj.add(point);
 * int param_2 = obj.count(point);
 */

4、2014. Longest Subsequence Repeated k Times

难度:Hard

思路

暂时不会。

代码

 //

你可能感兴趣的:(Leetcode周赛,leetcode,哈希,数组)