暑期Leetcode

1. 两数之和 简单

Code

 2. 两数相加 中等

Code

3. 无重复字符的最长子串 中等

/*
滑动窗口
用HashSet维护无重复子串
*/
class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> occ = new HashSet<Character>();
        int n = s.length();
        int R = -1, ans = 0;
        for (int i = 0; i < n; ++i) {
            if (i != 0) {
                occ.remove(s.charAt(i - 1));
            }
            while (R + 1 < n && !occ.contains(s.charAt(R + 1))) {
                occ.add(s.charAt(R + 1));
                ++R;
            }
            ans = Math.max(ans, R - i + 1);
        }
        return ans;
    }
}
Code

11. 盛最多水的容器 中等

Code

42. 接雨水 困难

Code

 130. 被围绕的区域 中等

Code

200. 岛屿数量 中等

class Solution {

    void dfs(char[][] grid, int r, int c) {
        int maxI = grid.length;
        int maxJ = grid[0].length;
        if (r < 0 || c < 0 || r >= maxI || c >= maxJ || grid[r][c] == '0') {
            return;
        }
        grid[r][c] = '0';        
        dfs(grid, r, c - 1);
        dfs(grid, r, c + 1);        
        dfs(grid, r - 1, c);
        dfs(grid, r + 1, c);
    }

    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        int maxI = grid.length;
        int maxJ = grid[0].length;
        int num = 0;
        for (int i = 0; i < maxI; i++) {
            for (int j = 0; j < maxJ; j++) {
                if (grid[i][j] == '1') {
                    ++num;
                    dfs(grid, i, j);
                }
            }
        }
        return num;
    }
}
Code

 

1010. 总持续时间可被 60 整除的歌曲 简单

/*
    模60剩余系。
    注意特殊处理30的情况。
*/
class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int len=time.length;
        int[] a = new int[60];
        int ans=0;
        for(int r : time)  a[r%60]++;
        for(int i=1;i<=29;i++) ans+=a[i]*a[60-i];
        if(a[0]>1){
            ans+=a[0]*(a[0]-1)/2;
        }
        if(a[30]>1){
            ans+=a[30]*(a[30]-1)/2;
        }
        return ans;
    }
}
Code

 

posted @ 2020-05-19 22:40  安月冷  阅读(157)  评论(0编辑  收藏  举报