您的位置:首页 > 编程语言 > Java开发

算法(Java)

2016-07-10 14:35 393 查看
*将字符串的空格用字符串%20替换,并输出替换后的字符串的长度(字符串用数组处理)

public int getNum(String[] str,int i){
int count = 0;
for (int i = 0; i < str.length;) {
if (str[i]==' '){
move(str,i+1,length+count*2-1);
str[i++]='%';
str[i++]='2';
str[i++]='0';
count++;
}
else {
i++;
}
}
return length + count*2;
}

public void move(char[] str,int start, int end) {
for (int end; i >= start; i--) {
str[i+2] = str[i];
}
}


*二分法

public class DichotomySearch {
public static void main(String[] args) {
int[] arr = new int[] { 12, 23, 34, 45, 56, 67, 77, 89, 90 };
System.out.println(search(arr, 12));
System.out.println(search(arr, 45));
System.out.println(search(arr, 67));
System.out.println(search(arr, 89));
System.out.println(search(arr, 99));
}

public static int search(int[] arr, int key) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int middle = (start + end) / 2;
if (key < arr[middle]) {
end = middle - 1;
} else if (key > arr[middle]) {
start = middle + 1;
} else {
return middle;
}
}
return -1;
}
}


*多边形重心问题

已知各个顶点的坐标求多边形面积

用叉乘(或者叫向量积)设多边形的点按某顺序依次是(x1,y1),(x2,y2),…,(xn,yn)我们任选一个点和每条边相连,相邻的边做叉乘再除以2(构成三角形的有向面积),一般我们选原点(0,0)则面积S=(x1y2-x2y1)/2+(x2y3-x3y2)/2+…+(xny1-x1yn)/2这里S是有向面积 还要取绝对值程序很简单了 如果数组标号是0到n-1则double s=0;for (int i=0;i

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while (n-- > 0) {
int m = input.nextInt();
Shape[] arr = new Shape[m + 1];
for (int i = 0; i < m; i++) {
double x = input.nextDouble();
double y = input.nextDouble();
arr[i] = new Shape(x, y);
}
double area = 0.0;//多边形面积
double Gx = 0.0, Gy = 0.0;// 重心的x、y
for (int i = 1; i <= m; i++) {
//核心代码
double temp=(arr[i%m].x*arr[i-1].y-arr[i%m].y*arr[i-1].x)/2.0;
area += temp;
Gx += temp * (arr[i % m].x + arr[i - 1].x) / 3.0;
Gy += temp * (arr[i % m].y + arr[i - 1].y) / 3.0;
}
if (area - 0 < 0.0000001) {
System.out.println("0.000 0.000");
continue;
}
System.out.print(String.format("%.3f %.3f\n",area,(Gx + Gy)/area));
}
}
}
class Shape {
double x = 0;
double y = 0;
Shape(double x, double y) {
this.x = x;
this.y = y;
}
}


*括号匹配问题

/**
* 进行匹配的算法。
* @param str 待检查的字符串。
* @return
*/
public static boolean match(String str) {
Stack stack = new Stack(); // 定义一个存放括号的栈。
char[] ca = str.toCharArray(); // 将字符串转为字符数组以便对其遍历。
stack.push((Character) ca[0]); // 首先将第一个字符压入栈中。
/*
* 从第二个字符开始,依次与栈中字符匹配。
* 成功则将栈顶元素弹出。
* 失败则将字符数组中的当前字符压入栈中。
*/
for (int index = 1; index < ca.length; ++index) {
Character c1 = (Character) stack.peek();
Character c2 = ca[index];
if ((c1.equals('(') && c2.equals(')'))
|| (c1.equals('[') && c2.equals(']'))) {
stack.pop();
} else {
stack.push(c2);
}
}
return stack.empty();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: