• 动态规划----求某一数组中的一个连续段的元素和


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

    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];
            }
        }
    
    }
  • 相关阅读:
    uc浏览器开发版
    探索.NET中的事件机制
    “多态枚举”数值如何判断?
    关于“程序集与命名空间”
    AutoResetEvent和ManualResetEvent的异同
    C# 获取DOS命令的返回值
    自定义控件——自绘
    关于using……的一些探讨
    XmlDocument操作xml类
    使用Trigger实现Cascading的功能
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/6405336.html
Copyright © 2020-2023  润新知