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

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

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]; } } 
}

转载于:https://www.cnblogs.com/maowuyu-xb/p/6405336.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值