三种算法求最大子段和问题——Java实现
给定由n个整数组成的序列(a1, a2, …, an),求该序列的子段和的最大值,当所有整数均为负整数时,其最大子段和为0。
LargestSubsegmentSum1.java //蛮力算法
import java.util.*;
public class LargestSubsegmentSum1
{
public static void main(String[] args)
{
/**
*从键盘输入所要求的序列的长度n
*/
Scanner in=new Scanner(System.in);
System.out.println("Please enter the length of segment you want to make(输入你要求的序列的长度):");
int n=in.nextInt();
/**
*从键盘输入所要求的序列,存储在a[n]中
*/
int[] a=new int[n];
System.out.println("Now,please enter the elements of the segment you want(现在请依次输入这个序列包含的元素(整数)):");
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
}
double startTime=System.currentTimeMillis();//starttime
/**
*求解最大子段和存在maxSum中
*/
int maxSum=a[0];
for(int i=0;i<n-1;i++)
{
int temp=a[i];
for(int j=i+1;j<n;j++)
{
temp+=a[j];
if(temp>maxSum)
maxSum=temp;
}
}
double endTime=System.currentTimeMillis();//endtime
/**
*打印输出求解结果和程序所用时间
*/
System.out.println("The largest sub-segment sum is(最大子段和是):"+maxSum);
System.out.println("Basic Statements take(基本语句用时) "+(endTime-startTime)+" milliseconds!");
}
}
****************************
相关文档:
Java学习从入门到精通
一、 JDK (Java Development Kit)
JDK是整个Java的核心,包括了Java运行环境(Java Runtime Envirnment),一堆Java工具和Java基础的类库(rt.jar)。不论什么Java应用服务器实质都是内置了某个版本的JDK。因此掌握JDK是学好Java的第一步。最主流的J ......
流 就是一根管子。流总是成对出现。
分为输入流、输出流。四个最近本的抽象类是:inputstream,outputstream.Reader与writer.前者是字节流,后者是字符流。
分为 字节流(8bit)、字符流(16bit)。
分为节点流(直接把管子放到目标上),处理流(把管子包装处理,如
bufferedwriter与bufferedreader
)
new FileOutputStr ......
来源:http://cj1240.zhmy.com/archives/2008/148832.html
JAVA 中的IO流
一、流的概念
流(stream)的概念源于UNIX中管道(pipe)的概念。在UNIX中,管道是一条不间断的字节流,用来实现程序或进程间的通信,或读写外围设备、外部文件等。
&nb ......
try{
URL url=new URL("http://baidu.com");
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
String s="";
StringBuffer sb=new StringBuffer("");
while((s=br.readLine())!=null) {   ......