法一:用链表来存数据,需要查找的时候,从头遍历取数据,最简单的思路,最麻烦的代码╮(╯_╰)╭
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];
}
}
}