码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-07-11 16:53:13      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:sse   暴力求解   size   main   ++   测试用例   sys   窗口   pac   

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的连续正数序列

标签:sse   暴力求解   size   main   ++   测试用例   sys   窗口   pac   

原文地址:https://www.cnblogs.com/fyusac/p/13283933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!