首页 > 代码库 > Java常用算法
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 = http://www.mamicode.com/0;>
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常用算法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。