zoukankan      html  css  js  c++  java
  • 动态规划----求某一数组中的一个连续段的元素和

    法一:用链表来存数据,需要查找的时候,从头遍历取数据,最简单的思路,最麻烦的代码╮(╯_╰)╭

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Scanner;

    //where  stands for dynamic programming
    public class ThreeZeroThree{
        //Initialize an array
        public static int[] NumArray() {
        ArrayList<Integer> list = new ArrayList<Integer>();
        
         System.out.print("please input a value of n to stands for the size of the array");    
         Scanner s=new Scanner(System.in);
         int n=s.nextInt();
         for(int i=0;i<n;i++){
            Scanner count=new Scanner(System.in);
            int value= count.nextInt();
            list.add(value);
           }
          int length=list.size();
          int[] array = new int[length];
          for(int j=0;j<length;j++)
          array[j]=list.get(j);
          return array;
             
            
        }
        
    public static void sumRange(int shuzi[],int a,int b){
        int sum=0;
        for(int k=a;k<=b;k++)
        sum=sum+shuzi[k];
        System.out.print(sum);
        
    }
            
    public static void main(String[] args){
        int a[]=NumArray();
         System.out.print("please input the value of The lower bound");    
         Scanner s=new Scanner(System.in);
         int n=s.nextInt();
         System.out.print("please input the value of The upper bound");    
         Scanner s2=new Scanner(System.in);
         int n2=s2.nextInt();
         sumRange(a,n,n2);
        
        }
        
        }

    动态规划,先把和存起来,就不用每次重复遍历。

    public class NumArray {
    
        public int[] sums;
    
        public NumArray(int[] nums) {
            if (nums == null) {
                sums = null;
            } else if (nums.length == 0) {
                sums = new int[0];
            } else {
                this.sums = new int[nums.length];
                sums[0] = nums[0];
                for (int i = 1; i < nums.length; i++) {
                    sums[i] = sums[i - 1] + nums[i];
                }
            }
        }
    
        public int sumRange(int i, int j) {
            if (sums == null) {
                return 0;
            }
            if (i >= sums.length || j >= sums.length || i > j) {
                return 0;
            } else if (i == 0) {
                return sums[j];
            } else {
                return sums[j] - sums[i - 1];
            }
        }
    
    }
  • 相关阅读:
    ASP.NET Core 问题排查:Request.EnableRewind 后第一次读取不到 Request.Body
    解决 AutoMapper ProjectTo 不起作用的问题
    解决 ASP.NET Core 自定义错误页面对 Middleware 异常无效的问题
    ASP.NET Core 从 gitlab-ci 环境变量读取配置
    终于解决 xUnit.net 测试中无法输出到控制台的问题
    ASP.NET Core 新建线程中使用依赖注入的问题
    前端回顾:2016年 JavaScript 之星
    前端工程师和设计师必读文章推荐【系列三十五】
    AsciiMorph
    Notyf
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/6405336.html
Copyright © 2011-2022 走看看