赞
踩
前60名有奖,搞了个62名,还是菜。
思路:直接求和就行,只是n为奇数的时候中间的数会计算两次,所以要减去一次。
- class Solution {
- public int diagonalSum(int[][] mat) {
-
- int sum = 0;
- int n = mat.length;
-
- for (int i = 0; i < n; i++)
- sum += mat[i][i];
-
- for (int i = 0; i < n; i++) {
- if (i == n - 1 - i)
- continue;
- sum += mat[i][n - 1 - i];
- }
-
- return sum;
-
- }
- }
思路:本质上就是找到三段中两个间隔内零的个数,直接相乘即可。当然要特判掉一些特殊情况(比如:全是0或者无法分成三段时)
- class Solution {
-
- static int mod = 1000000007;
-
- public int numWays(String s) {
-
- int sum = 0;
- long ans = 0;
- int n = s.length();
-
- for (int i = 0; i < n; i++) {
- if (s.charAt(i) == '1')
- sum++;
- }
-
- if (sum % 3 != 0)
- return 0;
-
- if (sum == 0) {
- ans = n - 1;
- ans = ans * (ans - 1) / 2 % mod;
- return (int) ans;
- }
-
- sum /= 3;
- int l = 0, r = n - 1, now = 0;
-
- for (; l < n && now < sum; l++) {
- if (s.charAt(l) == '1')
- now++;
- }
-
- now = 0;
- for (; r >= 0 && now < sum; r--) {
- if (s.charAt(r) == '1')
- now++;
- }
-
- long left = 0, right = 0;
- while (s.charAt(l) == '0') {
- left++;
- l++;
- }
- while (s.charAt(r) == '0') {
- right++;
- r--;
- }
-
- left++;
- right++;
-
- //System.out.println(l + " " + r);
-
- ans = left;
- ans = ans * right % mod;
-
- return (int) ans;
-
- }
- }
思路:这种类型的题基本就是换换包装,本质考察的知识一点没变,我们找到头和尾分别能组成的最长连续非递减子串,之后暴力左边的长度,然后二分右边的长度,中间的删掉,标记下最优答案即可。
- class Solution {
- public int findLengthOfShortestSubarray(int[] arr) {
-
- int n = arr.length;
-
- if (n <= 1) return 0;
-
- int l = 1, r = n - 2;
- while (l < n && arr[l] >= arr[l - 1]) l++;
- while (r >= 0 && arr[r] <= arr[r + 1]) r--;
-
- if (l == n || r < 0) return 0;
-
- //System.out.println(l + " " + r);
-
- int ans = Math.max(l, n - r - 1);
-
- for (int i = 0; i < l; i++) {
- int ls = r + 1, rs = n - 1, p = n;
- while (ls <= rs) {
- int mid = (ls + rs) / 2;
- if (arr[mid] >= arr[i]) {
- p = mid;
- rs = mid - 1;
- } else
- ls = mid + 1;
- }
- if (p != -1)
- ans = Math.max(ans, i + 1 + n - p);
- }
-
- return n - ans;
-
- }
- }
思路:可以考虑采用记忆化搜索,直接统计方案数。【时间复杂度较高】
- class Solution {
-
- private int n;
- private int[] locations;
- private int mod = 1000000007;
- private Map<String, Integer> map;
-
- public int countRoutes(int[] locations, int start, int finish, int fuel) {
-
- n = locations.length;
- map = new HashMap<>();
- this.locations = locations;
-
- return dfs(start, finish, fuel);
-
- }
-
- private int dfs(int u, int end, int fuel) {
-
- if (fuel < 0) return 0;
-
- if (fuel == 0)
- return u == end ? 1 : 0;
-
- String s = String.valueOf(u) + "#" + String.valueOf(fuel);
-
- if (map.containsKey(s))
- return map.get(s);
-
- long res = (u == end ? 1 : 0);
-
- for (int i = 0; i < n; i++) {
- if (i == u)
- continue;
- res = (res + dfs(i, end, fuel - Math.abs(locations[u] - locations[i]))) % mod;
- }
-
- map.put(s, (int) res);
-
- return (int) res;
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。