zoukankan      html  css  js  c++  java
  • 剑指Offer之和为S的连续正数序列

    题目描述

    小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
     
    思路:滑动窗口(双指针)
     
     1 import java.util.ArrayList;
     2 public class Solution {
     3     public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
     4        ArrayList<ArrayList<Integer>> array=new ArrayList<>();
     5         int plow=1,phigh=2;
     6         while(phigh>plow) {
     7             int psum=(phigh+plow)*(phigh-plow+1)/2;
     8             if(psum==sum) {
     9                 ArrayList<Integer> list=new ArrayList<>();
    10                 for(int i=plow;i<=phigh;i++)
    11                     list.add(i);
    12                 array.add(list);
    13                 plow++;
    14             }
    15             else if(psum<sum)
    16                 phigh++;
    17             else
    18                 plow++;
    19         }
    20         return array;
    21     }
    22 }
  • 相关阅读:
    ubuntu安装后要做什么
    JavaScript错误处理
    jQuery 事件
    display的用法
    百度排名的原理
    什么是ajax?
    CSS文档流
    引用CSS的方法
    jQuery的安装方式
    禁止WPS2019开机自启动
  • 原文地址:https://www.cnblogs.com/jacob-wuhan/p/13059359.html
Copyright © 2011-2022 走看看