新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-3-6
- 最后登录
- 1970-1-1
|
找到类似的第一题- Given a non-empty array nums contains positive integers and a positive integer target.
- Find the first subarray in nums that sums up to target and return the begin and end index of this subarray. If there is no such subarray, return [-1, -1].
- Example 1:
- Input: nums = [4, 3, 5, 7, 8], target = 12
- Output: [0, 2]
- Explanation: 4 + 3 + 5 = 12. Although 5 + 7 = 12, [4, 3, 5] is the first subarray that sums up to 12.
- Example 2:
- Input: nums = [1, 2, 3, 4], target = 15
- Output: [-1, -1]
- Explanation: Thers is no such subarray that sums up to 15.
复制代码 Solution:- private static int[] solution(final int[] array, final int target) {
- int start = 0;
- int end = 0;
- int sum = 0;
- int[] result = new int[2];
- while (end != array.length) {
- sum = sum + array[end];
- if (sum == target) {
- result[0] = start;
- result[1] = end;
- break;
- }
- if (sum > target) {
- sum = sum - array[start];
- start++;
- }
- if (sum < target) {
- end++;
- }
- }
- return result;
- }
复制代码 |
|