算法基础重构:
算法
1.一个有限指令集
2.接受一些输入(一些情况下不接受输入)
3.产生输出
4.一定在有限步骤之后终止
5.没一条指令必须: (1)有充分明确的目标,不可以有歧义
(2)计算机能处理的范围之内
(3)描述不依赖于任何一门编程语言以及具体的实现,主要是抽象出解决问题的思路
好的算法: 时间复杂度小,空间占比小,程序简洁(一般使用渐进表示法描述算法的时间复杂度)
一些常见时间复杂度
1.1基础编程模型
1.1.1java程序基本结构
原始数据类型:它们在计算机程序中精确定义整数,浮点数,布尔值。
语句:程序通过语句执行实现功能:6种语句(声明,赋值,条件,循环,调用,返回)
数组:多个同种数据类型的值的集合
静态方法:静态方法可以封装并重用代码,使得我们可以用独立的模块开发。
字符串:一连串的字符,java内置了对它们的一些操作。
标准输入/输出:输入输出是程序与外界链接的桥梁。
数据抽象:数据抽象封装和重用代码,使我们可以定义非原始数据类型,进而支持面向对象编程。
1.1.2原始数据类型与表达式
整型(int) 双精度实数类型(double)
布尔类型(true,false)
字符型(char)
java使用的是中缀表达式:一个字面量(或是一个表达式),紧接着是一个运算符,再接着是另一个字面量(或者另一个表达式)。
运算符优先级: *,/,%优先级高于+,-(优先级越高,越早运算)。逻辑运算符中,!拥有最高优先级,之后是&&,接着是||。一般来说,相同优先级的运算符运算顺序是从左到右。一般采取括号比较好。
64位整数: long
16:short
32:int
16位字符:char
8位整数: byte
32位单精度实数:float
类型转换:低精度到高精度,自动转换,且不会损失精度值(eg:1+2.78),高精度到低精度需要强制转换,会损失一定的精度值(eg:2.98(int))。
比较运算符: <=,>=,==,!=,这些都是混合运算符,还有>,<两个比较运算符。
自增自减(++,–)i++在程序中会执行,但是先使用未加的i再执行自增,具体根据情况而定。
布尔型的表达式被称为布尔表达式
1.1.3语句
声明(关键字),赋值(=),条件(if else),循环(for,while),调用(函数名();和对象或者类的.方法名();),控制(break,continue),返回(return)这7类语句
一般代码结构都是具有一定的框架并且是嵌套的:eg:循环嵌套
1.1.4简便记法
1.1.5数组
创建并初始化数组3步走战略:1.声明数组的名字和类型,2创建数组,3,初始化数组元素
eg:
double[] a;
a=new double[N];
for(int i=0;i<N;i++)
a[i]=0.0;//初始化数组
简化写法: double[] a=new double[N];;
声明初始化:int[] a={1,2,3,4,5,6};
典型数组处理代码:
1.找出数组中最大元素
double max=a[0];
for(int i=1;i<a.length;i++)
if(a[i]>max) max=a[i];
2.计算数组元素平均值
int N=a.length;
double sum=0.0;
for(int i=0;i<N;i++)
sum+=a[i];
double average=sum/N;
3.复制数组
package java1;
public class f {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int i;
int[] a= {1,2,3,4,5,6,7};
int N=a.length;
int[] b=new int[N];
for(i=0;i<N;i++) {
b[i]=a[i];
System.out.println(b[i]);
}
}
}
4.颠倒数组元素的顺序
int N=a.length;
for(int i=0;i<N/2;i++){
double temp=a[i];
a[i]=a[N-1-i];
a[N-1-i]=temp;
}
5.矩阵相乘
int N=a.length;
double[][] c=new double[N][N];
for(int i=0;i<N;i++)
for(int j=0;j<N;j++){
//计算行i和列j的点乘
for(int k=0;k<N;k++)
c[i][j]+=a[i][k]*b[k][j];
}
6.二维数组
double[][] a=new double[M][N];
1.1.6静态方法
目前学习的所有java程序要么是数据类型的定义,要么是一个静态方法库。
典型静态方法的实现:
计算一个整数的绝对值
public static int abs(int x){
if(x<0) return -x;
else return x;
计算一个浮点数的绝对值
public static double abs(double x){
if(x<0.0) return -x;
else return x;
}
判断一个数是否是素数
public static boolean isPrime(int N){
if(N<2) return false;
for(int i=2;i*i<=N;i++)
if(N%i==0) return false;
return true;
}
计算平方根
public static double sqrt(double c){
if(c<0) return Double.NaN;
double err=1e-15;
double t=c;
while(Math.abs(t-c/t)>err*t;
t=(c/t+t)/2.0;
return t;
}
计算三角形的斜边
public static double hypotenuse(double a,double b){
return Math.sqrt(a*a+b*b);
计算调和级数
public static double H(int N){
double sum=0.0;
for(int i=1;i<=N;i++)
sum+=1.0/i;
return sum;
}
1.1.7API
1.1.8字符串
1.1.9输入输出
1.1.10二分查找
1.1.11展望
第一个算法:2300多年前的欧几里得算法:
计算两个非负整数p和q的最大公约数:若q是0,则最大公约数是p,否则,将p除以q得到余数
r,p和q的最大公约数即为q和r的最大公约数。
java语言描述:
public static int gcd(int p,int q){
if(q==0) return p;
int r=p%q;
return gcd(q,r);
}