第一题
给定01数组和一个数字k,选择k个为0的数字变成1,使得连续出现的1的个数最多
用的暴力回溯
static int res = Integer.MIN_VALUE; public static int GetMaxConsecutiveOnes (int[] nums, int k) { // write code here dfs(nums,k,0); return res == Integer.MIN_VALUE? -1 : res; } private static void dfs(int[] nums,int k,int idx){ if(idx == k + 1){ return; } int n = nums.length; for(int i = 0;i < n;i++) { int tmp = 0; while (i < n && nums[i] == 1) { tmp++; i++; } res = Math.max(res, tmp); } for (int i = 0; i < n; i++) { if(nums[i] == 0){ nums[i] = 1; dfs(nums,k,idx+1); nums[i] = 0; } } }
第二题
螺旋矩阵,Leetcode的原题
public static int[] SpiralMatrix (int[][] matrix) { // write code here int top = 0,left = 0; int rows = matrix.length,cols = matrix[0].length; int a = rows,b = cols; List<Integer> res = new ArrayList<>(); int i = 0; while(top < rows && left < cols){ while(left < cols){ res.add(matrix[top][left]); left++; } left--; top++; while(top < rows){ res.add(matrix[top][left]); top++; } top--; left--; if(res.size() == a * b) break; while(left >=i){ res.add(matrix[top][left]); left--; } left++; top--; while(top > i){ res.add(matrix[top][left]); top--; } top++; left++; rows--; cols--; i++; } int[] ans = new int[res.size()]; int j = 0; for (Integer re : res) { ans[j++] = re; } return ans; }
第三题
字符串碎片的平均长度
public static int GetFragment (String str) { // write code here if(str.length() == 0) return 0; List<Integer> list = new ArrayList<>(); StringBuilder sb = new StringBuilder(str); sb.append('!'); for (int i = 1; i < sb.length(); i++) { int cnt = 1; while(sb.charAt(i-1) == sb.charAt(i)){ cnt+=1; i++; } list.add(cnt); } System.out.println(list); long sum = 0; for (Integer val : list) { sum += val; } return (int)sum/list.size(); }
全部评论
(0) 回帖