java算法小例子
作为一个程序员,有时候我觉得自己都不适合,因为自己数学不好,算法不好,脑子不够灵活。而对于算法,感觉就像是数学题,总觉得很难。以前上学,在班里总有几个什么都不好,但唯独数学很厉害,真气人!面对难题时,我只能求助,自己想破脑瓜子都想不出什么好的解决办法,都不知道怎么提高这方面的能力。只能慢慢学习了。
自己买了本算法的书,有空的时候就看看,写一写,总是收获的!下面是几个例子:
1.判断闰年
public class LeapYear {
public static int leapYear(int year) {
if ((year % 400 == 0) || (year % 100 != 0) && (year % 4 == 0)) {
return 1; //is leap year
} else {
return 0; //not a leap year
}
}
public static void main(String[] args) {
int year;
int count = 0;
System.out.println("2000年到3000年之间所有的闰年如下:");
for (year = 2000; year <= 3000; year++) {
if (leapYear(year) == 1) {
System.out.print(year + " ");
count++;
if (count % 16 == 0) {
System.out.println();
}
}
}
System.out.println("一共有" + count + "个闰年!");
}
}
2.水仙花数
public class NarcissusNum {
public static void narcissusNum(int n) {
long i,start,end,temp,num,sum;
int j;
start = (long) Math.pow(10, n - 1);
end = (long) (Math.pow(10, n) - 1);
for (i = start; i <= end; i++) {
temp = 0;
num = i;
sum = 0;
for (j = 0; j < n; j++) {
temp = num % 10;
sum = (long) (sum + Math.pow(temp, n));
num = (num - temp) / 10;
}
if (sum == i) {
System.out.printf("%d\n", i);
}
}
}
public static void main(String[] args) {
int n;
n = 3;
System.out.printf("列举%d位的水仙花数:\n", n);
narcissusNum(n);
System.out.println();
n = 4;
System.out.printf("列举%d位的水仙花数:\n", n);
narcissusNum(n);
System.out.printf("\n");
}
}
3.判断素数
public class IsPrime {
public static int isPrime(int a) {
for (int i = 2; i < a; i++) {
if (a % i == 0) {
return 0; //not prime number
}
}
return 1; //is a prime number
}
public static void main(String[] args) {
int i,n,count;
n = 1000;
count = 0;
System.out.println("列举1~1000之间所有的素数");
for (i = 1; i < 1000; i++) {
if (isPrime(i) == 1) {
System.out.printf("%7d", i);
count++;
if (count % 10 == 0) {
System.out.println();
}
}
}
System.out.println();
}
}
4. List去重
public static List removeByFor(List list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(i).equals(list.get(j))) {
list.remove(j);
}
}
}
return list;
}
public static List removeBySet(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
return list;
}
public static List removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object element = iterator.next();
if (set.add(element)) {
newList.add(element);
}
}
list.clear();
list.addAll(newList);
return list;
}
public static List removeByContain(List list) {
List tempList = new ArrayList();
for (int i = 0;i < list.size(); i++) {
if (!tempList.contains(list.get(i))) {
tempList.add(list.get(i));
}
}
return tempList;
}
5.Map与Bean相互转换
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null) {
return null;
}
ConvertUtils.register((aClass, o) -> {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return simpleDateFormat.parse(o.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}, Date.class);
Object obj = beanClass.newInstance();
BeanUtils.populate(obj, map);
return obj;
}
public static Map<String, Object> objectToMap(Object obj) throws Exception {
return BeanUtils.describe(obj);
}
public static Map<String, Object> objectToMapTwo(Object obj) throws Exception {
if (obj == null) {
return Maps.newHashMap();
}
Map<String, Object> map = Maps.newHashMap();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
public static Object mapToObjectTwo(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null) {
return null;
}
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
6.排序
//插入
public static void insertSort(int[] a) {
int length = a.length;
for (int i = 1; i < length; i++) {
int insertNum = a[i];
int j = i - 1;
while (j >= 0 && a[j] > insertNum) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = insertNum;
}
}
//希尔
public static void sheelSort(int a[]) {
int length = a.length;
for (int gap = length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < length; i++) {
int insertNum = a[i];
int j = i - gap;
while (j >= 0 && a[j] > insertNum) {
a[j + gap] = a[j];
j -= gap;
}
a[j + gap] = insertNum;
}
}
}
//冒泡
public static void bubble(int[] a) {
int length = a.length;
int temp;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
//简单选择排序
public static void selectSort(int[] a) {
int length = a.length;
for (int i = 0; i < length; i++) {
//记录当前最小数和位置
int key = a[i];
int position = i;
for (int j = i + 1; j < length; j++) {
if (key > a[j]) {
key = a[j];
position = j;
}
}
//交换
a[position] = a[i];
a[i] = key;
}
}
//快速排序
public static void quickSort(int[] a, int start, int end) {
if (a == null || start >= end) return;
int key = a[start];
int i = start, j = end;
while (i < j) {
while (i < j && a[j] >= key) {
j--;
}
if (i < j) {
a[i++] = a[j];
}
while (i < j && a[i] <= key) {
i++;
}
if (i < j) {
a[j--] = a[i];
}
}
a[i] = key;
quickSort(a, start, i - 1);
quickSort(a, i + 1, end);
}
//基数排序
public static void radixSort(int[] a) {
int queueNum = 10;
int length = a.length;
//找到最大数,判断位数
int max = a[0];
for (int i = 1; i < length; i++) {
if (a[i] > max) {
max = a[i];
}
}
int times = 0;
while (max > 0) {
max /= 10;
times++;
}
//初始化10个队列
ArrayList<ArrayList> queue = new ArrayList<>();
for (int i = 0; i < queueNum; i++) {
ArrayList<Integer> queue1 = new ArrayList<>();
queue.add(queue1);
}
for (int i = 0; i < times; i++) {
//分配数组元素
for (int j = 0; j < length; j++) {
//得到位数
int x = a[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
ArrayList<Integer> queue2 = queue.get(x);
queue2.add(a[j]);
queue.set(x, queue2);
}
//记录元素数
int count = 0;
//收集队列元素
for (int k = 0; k < queueNum; k++) {
while (queue.get(k).size() > 0) {
ArrayList<Integer> queue3 = queue.get(k);
a[count] = queue3.get(0);
queue3.remove(0);
count++;
}
}
}
}
//堆排序
public static void heapSort(int[] a) {
int length = a.length;
for (int i = 0; i < length - 1; i++) {
adjustHeap(a, length - i - 1);
swap(a, 0, length - i - 1);
}
}
public static void adjustHeap(int[] a, int lastIndex) {
for (int i = (lastIndex - 1) / 2; i >= 0 ; i--) {
int k = i;
while (2*k + 1 <= lastIndex) {
int left = 2*k + 1;
if (left < lastIndex && a[left] < a[left + 1]) {
left++;
}
if (a[k] >= a[left]) break;
swap(a, k, left);
k = left;
}
}
System.out.println("调整后" + Arrays.toString(a));
}
//归并排序
public static void mergeSortTwo(int[] a, int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
mergeSortTwo(a, start, mid);
mergeSortTwo(a, mid + 1, end);
mergeTwo(a, start, mid, end);
}
}
public static void mergeTwo(int[] a, int start, int mid, int end) {
int[] temp = new int[a.length];
int p1 = start, p2 = mid + 1, k = start;
while (p1 <= mid && p2 <= end) {
if (a[p1] <= a[p2]) {
temp[k++] = a[p1++];
} else {
temp[k++] = a[p2++];
}
}
while (p1<=mid) {
temp[k++] = a[p1++];
}
while (p2<=end) {
temp[k++] = a[p2++];
}
for (int i = start; i <= end; i++) {
a[i] = temp[i];
}
}
java算法小例子的更多相关文章
- java反射小例子
package com.txwsqk.reflect; public class Car { private String brand; private String color; private i ...
- JSP调用JAVA方法小例子
用JAVA编写的函数 package doc; //定义一个包 public class Dy { //定义一个类 public static int Sub(int x,int y){ //定义函数 ...
- java算法小知识练习
偶尔翻开了以前的练习题,不自觉又想随手敲一遍,虽然有些思想依然是那么老套,但毕竟也算是对知识的巩固 了. 一.题目:有1.2.3.4四个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? 具体 ...
- Java——多线程小例子
body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...
- LigerUI java SSH小例子
1.新建web project 2.ssh框架 加入到项目中去(这里不介绍,网上搜索) 3.struts2配置 http://www.cnblogs.com/istianyu/archive/2013 ...
- 一个Java线程小例子(仿火车票售卖)
public class MyThread extends Thread{ private static int ticket=100; public void run(){ for(int i=0; ...
- JS各种算法小例子
<!DOCTYPE html><html><head> <title>js</title> <meta charset=& ...
- java算法小知识练习(二)
话不多说,直接上题: 题目:两个乒乓球队进行比赛,各出三人.甲队为a,b,c三人,乙队为x,y,z三人.已抽签决定比赛名单. 有人向队员打听比赛的名单.a说他不和x比,c说他不和x,z比,请编程序 ...
- java死锁小例子
package cn.com.io.threadDemo.ThreadSyn; /** * 通过两个属性值创建死锁 * 本程序通过两个线程各自锁定一个属性值,这样两个线程都无法结束,造成死锁 * @a ...
随机推荐
- P3572 [POI2014]PTA-Little Bird
P3572 [POI2014]PTA-Little Bird 一只鸟从1跳到n.从1开始,跳到比当前矮的不消耗体力,否则消耗一点体力,每次询问有一个步伐限制k,求每次最少耗费多少体力 很简短的题目哼. ...
- Hadoop生态圈-桶表和分区表
Hadoop生态圈-桶表和分区表 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.
- [Java] 集合框架原理之一:基本结构与源码分析
一.Collection Collection 接口定义了一些基本的方法: int size(); boolean isEmpty(); boolean add(E e); boolean addAl ...
- Maven学习二:使用Nexus搭建Maven私服及相关配置
处于安全等原因的考虑,一些企业内部网络是不允许访问外部网络的,但是项目内部搭建的项目又是Maven架构,这样就需要企业在内部网络中搭建自己的Maven仓库服务,再者一些大型企业或者内部模块化组件化划分 ...
- NOIP2011 提高组 Day2
自测时间:2017.4.12 8:15——11:45 实际得分:100+0+0=100 期望得分:100+100+0=260 T2 符合要求的总价值*符合要求的总个数 写成:符合要求的总价值*区间总个 ...
- HDU 4135 容斥
问a,b区间内与n互质个数,a,b<=1e15,n<=1e9 n才1e9考虑分解对因子的组合进行容斥,因为19个最小的不同素数乘积即已大于LL了,枚举状态复杂度不会很高.然后差分就好了. ...
- android 低功耗蓝牙使用
参考链接:http://blog.csdn.net/xubin341719/article/details/38584469 1.android 手机的低功耗蓝牙,又称BLE :BLE在andriod ...
- [转载]PayPal为什么从Java迁移到Node.js,性能提高一倍,文件代码减少44%
http://ourjs.com/detail/52a914f0127c763203000008 大家都知道PayPal是另一家迁移到Node.js平台的大型公司,Jeff Harrell的这篇博文 ...
- 【leetcode 简单】 第六十四题 翻转二叉树
翻转一棵二叉树. 示例: 输入: 4 / \ 2 7 / \ / \ 1 3 6 9 输出: 4 / \ 7 2 / \ / \ 9 6 3 1 备注: 这个问题是受到 Max Howell的 原问题 ...
- 【leetcode 简单】 第五十六题 快乐数
编写一个算法来判断一个数是不是“快乐数”. 一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1.如 ...