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 }
  • 相关阅读:
    开启sentry权限控制hue
    hive_server2的权限控制
    自带的simple认证
    tableau备份
    tableau分布式添加节点
    升级tableau版本
    tableau日常管理
    mavn Nexus Repository Manager漏洞
    第3章:打造命令行工具
    基于从库+binlog方式恢复数据
  • 原文地址:https://www.cnblogs.com/jacob-wuhan/p/13059359.html
Copyright © 2011-2022 走看看