欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > java >内容正文

java

leetcode 927. Three Equal Parts | 927. 三等分(Java)

发布时间:2024/2/28 java 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode 927. Three Equal Parts | 927. 三等分(Java) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

https://leetcode.com/problems/three-equal-parts/

题解

不知道为什么是 hard,感觉这道题没有套路(印象中这几道 hard 都没有什么套路,这就是 hard 的原因吗),甚至没有 get 到这题的难点是什么,大概是在考察分析问题的能力吧。

分析完之后,思路很简单。先算总共有多少个 1,就可以分离出右边的部分了。然后根据右边的部分,匹配出左边部分和中间部分。

class Solution {public int[] threeEqualParts(int[] arr) {int leftEnd, midEnd, rightBegin;// 统计每个相同部分中1的个数int count = 0;for (int n : arr)count += n;if (count == 0) return new int[]{0, arr.length - 1};if (count % 3 != 0) return new int[]{-1, -1};count /= 3;// 分离最后一个部分int cnt = 0;int i;for (i = arr.length - 1; cnt < count; i--) {cnt += arr[i];}rightBegin = i + 1;// 分离第一个部分,并验证其与最后一个部分相同i = 0;while (arr[i] != 1) i++;int j = rightBegin;while (j < arr.length) {if (arr[i++] != arr[j++]) return new int[]{-1, -1};}// 分离中间部分,并验证其与最后一个部分相同leftEnd = i - 1;while (arr[i] != 1) i++;j = rightBegin;while (j < arr.length) {if (arr[i++] != arr[j++]) return new int[]{-1, -1};}midEnd = i;return new int[]{leftEnd, midEnd};} }

总结

以上是生活随笔为你收集整理的leetcode 927. Three Equal Parts | 927. 三等分(Java)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。