剑指offer57 和为s的连续正数序列

Posted fyusac

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer57 和为s的连续正数序列相关的知识,希望对你有一定的参考价值。

package com.example.lettcode.offer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Class FindContinuousSequence
 * @Description 剑指offer57 和为s的连续正数序列
 * @Author 
 * @Date 2020/7/11
 **/
public class FindContinuousSequence {    
}
/**
 * 解法1:暴力求解
 */
public static int[][] findContinuousSequence(int target) {
	List<List<Integer>> ans = new ArrayList<>();
	int left = 1;
	int middle = target / 2;
	for (int i = left; i <= middle; i++) {
		int sum = 0;
		List<Integer> integerList = new ArrayList<>();
		for (int j = i; j <= target; j++) {
			sum += j;
			integerList.add(j);
			if (sum == target) {
				ans.add(integerList);
				break;
			}
			if (sum > target) break;
		}
	}
	int[][] result = new int[ans.size()][];
	for (int i = 0; i < ans.size(); i++) {
		int len = ans.get(i).size();
		result[i] = new int[len];
		for (int j = 0; j <len; j++) {
			result[i][j] = ans.get(i).get(j);
		}
	}

	return result;
}
/**
 * 解法2:滑动窗口
 */
public static int[][] findContinuousSequence(int target) {
	int left = 1, right = 1;    // 滑动窗口的两个边界指针
	int sum = 0;
	int middle = target / 2;
	List<int[]> res = new ArrayList<>();
	while (left <= middle) {
		if (sum < target) {
			// 右边界右移
			sum += right;
			right++;
		} else if (sum > target) {
			// 左边界右移
			sum -= left;
			left++;
		} else {
			int[] temp = new int[right-left];
			for (int i = left; i < right; i++) {
				temp[i-left] = i;
			}
			res.add(temp);
			// 左边界右移
			sum-=left;
			left++;
		}
	}
	return res.toArray(new int[res.size()][]);
}
// 测试用例
public static void main(String[] args) {
	int target = 9;
	int[][] ans = findContinuousSequence(target);
	System.out.println("FindContinuousSequence demo01 result:");
	for (int i = 0; i < ans.length; i++) {
		for (int j = 0; j < ans[i].length; j++) {
			System.out.print(" " + ans[i][j]);
		}
		System.out.println("");
	}
	System.out.println("");

	target = 15;
	ans = findContinuousSequence(target);
	System.out.println("FindContinuousSequence demo02 result:");
	for (int i = 0; i < ans.length; i++) {
		for (int j = 0; j < ans[i].length; j++) {
			System.out.print(" " + ans[i][j]);
		}
		System.out.println("");
	}
	System.out.println("");
}

以上是关于剑指offer57 和为s的连续正数序列的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Algorithm 剑指 Offer 57 - II. 和为s的连续正数序列

剑指offer-面试题57_2-和为s的连续正数序列-穷举法

[LeetCode]剑指 Offer 57 - II. 和为s的连续正数序列

剑指offer双指针 57-II.和为s的连续正数序列

Leetcode剑指 Offer 57 - II. 和为s的连续正数序列(双指针)

LeetCode剑指offer57 II和为s的连续正数序列(用vector模拟滑动窗口)