可以直接使用set集合,边存边添加,递增序列,有序会想到二分,但是还是滑动窗口的双指针算法比较快。
public int[] twoSum1(int[] nums, int target) {
HashSet<Integer> set = new HashSet<>();
for(int e : nums){
int num = target - e;
if(set.contains(num)){
return new int[]{e,num};
}
set.add(e);
}
return new int[]{};
}
public int[] twoSum2(int[] nums, int target) {
int right = nums.length - 1;
for(int i = 0;i < nums.length;i++){
if (nums[i] >= target) {
right = i - 1;
break;
}
}
for (int i = 0; i < right; i++) {
if(binarySearch(nums,i + 1,right,target - nums[i])){
return new int[]{nums[i],target - nums[i]};
}
}
return new int[]{};
}
private boolean binarySearch(int[] nums, int left, int right, int target) {
while (left <= right){
int mid = left + (right - left) / 2;
if (nums[mid] == target){
return true;
}
if (nums[mid] > target){
right = mid - 1;
} else {
left = mid + 1;
}
}
return false;
}
滑动窗口:O(n)
代码思想来自评论区:
public int[] twoSum3(int[] nums, int target) {
int left = 0,right = nums.length - 1;
while (left < right){
if (nums[left] + nums[right] > target){
right--;
} else if (nums[left] + nums[right] < target){
left++;
} else {
return new int[]{nums[left],nums[right]};
}
}
return new int[]{};
}
57.连续递增序列的和问题
自己写的前缀和的计算,因为调用集合函数比较多,比较慢。
public int[][] findContinuousSequence1(int target) {
int[] prefix = new int[target / 2 + 2];
prefix[0] = 0;
HashMap<Integer, Integer> subMap = new HashMap<>();
for (int i = 1; i < prefix.length; i++) {
prefix[i] = prefix[i - 1] + i;
subMap.put(prefix[i],i);
}
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < prefix.length; i++) {
int num = prefix[i] + target;
if (subMap.containsKey(num)){
map.put(i + 1,subMap.get(num));
}
}
if (map.size() != 0) {
int[][] res = new int[map.size()][];
int index = 0;
for(Map.Entry<Integer,Integer> entry : map.entrySet()){
int[] sub = new int[entry.getValue() - entry.getKey() + 1];
int subIndex = 0;
for (int i = entry.getKey(); i <= entry.getValue(); i++) {
sub[subIndex++] = i;
}
res[index++] = sub;
}
return res;
}
return new int[][]{};
}
还是滑动窗口的操作,很快,时间复杂度在O(n),代码也很简洁,注意的地方是,需要证明出来,滑动窗口一定可以实现把所有满足条件的数组全找出来。
代码来源:
https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/shi-yao-shi-hua-dong-chuang-kou-yi-ji-ru-he-yong-h/
public int[][] findContinuousSequence2(int target) {
int index = target / 2 + 1;
int left = 1,right = 1;
int sum = 0;
List<int[]> list = new ArrayList<>();
while (left < index){
if (sum == target) {
int[] sub = new int[right - left];
for (int i = 0; i < sub.length; i++) {
sub[i] = left + i;
}
list.add(sub);
sum -= left;
left++;
} else if (sum < target){
sum += right;
right++;
} else {
sum -= left;
left++;
}
}
return list.toArray(new int[list.size()][]);
}