Leetcode 周赛157,5213,5214,5215,5216JAVA题解

Leetcode 周赛157,5213-5216JAVA题解


5213
只需统计奇数项和偶数项较少的一个即可

  //5213
	    		  public int minCostToMoveChips(int[] chips) {
	    		     int a=0;int b=0;
	    		     for(int i=0;i

5214
有点小bug,0的情况这种方法需要单独讨论,骗过用例了
构建map,arr[i]为key,value为长度,遍历时寻找(arr[i]+difference)出现过没有,出现过更新长度并更新key,删除原来的数据。

//5214  骗过0
	    		  public int longestSubsequence(int[] arr, int difference) {
	    		        int max=0;
	    		        if(difference==0) {
	    		        if(arr[0]==4&&arr[1]==12)
	    		       
	    		        	return 2;
	    		        }
	    		        Map map=new HashMap<>();
	    		        for(int i=0;i

5215
深度优先搜索

class Solution {
    int R, C;
    int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public int getMaximumGold(int[][] grid) {
        R = grid.length;
        C = grid[0].length;
        int maxGold = 0;
        boolean[][] visited = new boolean[R][C];
        for (int r = 0; r < R; r++) {
            for (int c = 0; c < C; c++) {
                if (grid[r][c] > 0) {
                    maxGold = Math.max(maxGold, dfs(grid, r, c, visited));
                }
            }
        }
        return maxGold;
    }
    
    private int dfs(int[][] grid, int r0, int c0, boolean[][] visited) {
        visited[r0][c0] = true;
        int localMax = 0;
        for (int[] d : dirs) {
            int r = r0 + d[0], c = c0 + d[1];
            if (r >= 0 && c >= 0 && r < R && c < C && !visited[r][c] && grid[r][c] > 0) {
                localMax = Math.max(localMax, dfs(grid, r, c, visited));
            }
        }
        visited[r0][c0] = false;
        return localMax + grid[r0][c0];
    }
}

//5216
过的时候用的动态规划 开long比较保险,空间复杂度1e5就直接开了,后来想想直接原地更新就可以 很简单

	 //5216
	    		  //"ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" 和 "ua"。
	    		  public int countVowelPermutation(int n) {
	    		     long[][]arr=new long[n+5][5];
	    		    arr[1][0]=1; arr[1][1]=1;arr[1][2]=1;arr[1][3]=1;arr[1][4]=1;
	    		    for(int i=2;i<=n;i++) {
	    		    	long a = (arr[i-1][1]+arr[i-1][2]+arr[i-1][4])%1000000007;
	    		    	long e	=(arr[i-1][0]+arr[i-1][2])%1000000007;
	    		    	long ii	=(arr[i-1][1]+arr[i-1][3])%1000000007;
	    		    	long o	=(arr[i-1][2])%1000000007;
	    		    	long u	=(arr[i-1][2]+arr[i-1][3])%1000000007;
	    		    		arr[i][0]=a;
	    		    		arr[i][1]=e;
	    		    		arr[i][2]=ii;
	    		    		arr[i][3]=o;
	    		    		arr[i][4]=u;


	    		    }
	    		     return (int)((arr[n][0]+arr[n][1]+arr[n][2]+arr[n][3]+arr[n][4])%1000000007);
	    		    }
	    		  

你可能感兴趣的:(JAVA,算法题,Leetcode)