Java常用算法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java常用算法相关的知识,希望对你有一定的参考价值。
2017-07-06
1 去重
1.1 去重
//去重复,需要额外定义一个List public static void RemoveRepeat(List<Integer> arrs) { List<Integer> tmp = new ArrayList<Integer>(); Iterator<Integer> it = arrs.iterator(); while (it.hasNext()) { int a = it.next(); if (tmp.contains(a)) it.remove(); else tmp.add(a); } }
1.2 去不重
// 去不重复的数,用的是选择排序算法变化版 public static void RemoveNoRepeat(List<Integer> arrs) { Boolean isRepeate = false; for (int i = 0; i < arrs.size(); i++) { isRepeate = false; for (int j = 0; j < arrs.size(); j++) { if (arrs.get(i) == arrs.get(j) && i != j) { isRepeate = true; break; } } if (!isRepeate) { arrs.remove(i); i--; } } } public static void RemoveNoRepeatImprove(List<Integer> arrs) { Boolean isRepeate = false; for (int i = arrs.size() - 1; i >= 0; i--) { isRepeate = false; for (int j = arrs.size() - 1; j >= 0; j--) { if (arrs.get(i) == arrs.get(j) && i != j) { isRepeate = true; break; } } if (!isRepeate) { arrs.remove(i); } } } public static void RemoveNoRepeatWithExtraMap(List<Integer> arrs) { Map<Integer, Integer> repeat = CountRepeat(arrs); for (int i = arrs.size() - 1; i >= 0; i--) { if (repeat.get(arrs.get(i)) == 1) { arrs.remove(i); } } } // 统计重复数 public static Map<Integer, Integer> CountRepeat(List<Integer> arrs) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Integer value = 0; for (Integer arr : arrs) { if (map.containsKey(arr)) { value = map.get(arr); map.put(arr, value + 1); } else { map.put(arr, 1); } } return map; }
2 随机分配
public static Map<String, String> TicketDispatch(List<String> customers, List<String> tickets) { Map<String, String> result = new HashMap<String, String>(); Random r = new Random(); int iCustomer; int iTicket; for (int i = customers.size(); i > 0; i--) { // 取值范围[0,i) iCustomer = r.nextInt(i); iTicket = r.nextInt(tickets.size()); result.put(customers.get(iCustomer), tickets.get(iTicket)); customers.remove(iCustomer); tickets.remove(iTicket); } return result; }
3 递归
//Java递归删除一个目录下文件和文件夹 private static void deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); // 递归删除目录中的子目录下 for (int i=0; i<children.length; i++) { deleteDir(new File(dir, children[i])); } } dir.delete(); }
以上是关于Java常用算法的主要内容,如果未能解决你的问题,请参考以下文章