给定一个含有 n
个正整数的数组和一个正整数 target
。
找出该数组中满足其总和大于等于 target
的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr]
,并返回其长度。如果不存在符合条件的子数组,返回 0
。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0;
int right = 0;
int n = nums.length;
int sum = 0;
int l = Integer.MAX_VALUE;
if (nums.length == 0) {
return 0;
}
while (right < n) {
sum += nums[right];
while (sum >= target) {
l = Math.min(l, right - left + 1);
sum -= nums[left];
left++;
}
right++;
}
return l == Integer.MAX_VALUE ? 0 : l;
}
}
/*
滑动窗口,因为要找连续的最短子序列,小于target就加入右端值,大于就减去左端值*/
给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
import java.util.Arrays;
class Solution {
public int longestConsecutive(int[] nums) {
Arrays.sort(nums);
int left = 0;
int right = 1;
int length = 1;
int sLength = 1;
if (nums.length == 0) {
return 0;
}
while (right < nums.length && left < nums.length) {
if (nums[right] == nums[right - 1] + 1) {
length++;
right++;
} else if (nums[right] == nums[right - 1]) {
right++;
} else {
left = right;
right = left + 1;
length = 1;
}
if (sLength < length) {
sLength = length;
}
}
return sLength;
}
}
给你两个按 非递减顺序 排列的整数数组 nums1
和 nums2
,另有两个整数 m
和 n
,分别表示 nums1
和 nums2
中的元素数目。
请你 合并 nums2
到 nums1
中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1
中。为了应对这种情况,nums1
的初始长度为 m + n
,其中前 m
个元素表示应合并的元素,后 n
个元素为 0
,应忽略。nums2
的长度为 n
。
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int tail = m + n - 1;// 合并后数组长度
int p1 = m - 1;
int p2 = n - 1;
while (p1 >= 0 || p2 >= 0) {
if (p1 == -1) {
nums1[tail--] = nums2[p2--];
} else if (p2 == -1) {
nums1[tail--] = nums1[p1--];
} else if (nums1[p1] > nums2[p2]) {
nums1[tail--] = nums1[p1--];
} else {
nums1[tail--] = nums2[p2--];
}
}
}
}