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];
            }
        }
    
    }
  • 相关阅读:
    Vue_使用v-model指令写的简易计算器
    Vue_v-for的四种用法示例
    bs4_加载顺序
    Vue_自定义指令
    Vue_v-for中key的使用注意事项
    Vue_指令
    bs4_card(卡片)
    Vue_过滤器
    Vue_生命周期函数
    selenium 文件上传
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/6405336.html
Copyright © 2011-2022 走看看