Docsity

Algorithms and Data Structures: A Comprehensive Guide with Code Examples, Cheat Sheet of Introduction to Computers

Partial preview of the text

Download Algorithms and Data Structures: A Comprehensive Guide with Code Examples and more Cheat Sheet Introduction to Computers in PDF only on Docsity!

Res.contains(str) check

High Five

public static Map<Integer, Double> getHighFive(List scores) { Map<Integer, PriorityQueue> scoreMap = new HashMap<Integer, PriorityQueue>(); for(Node s : scores){ scoreMap.putIfAbsent(s.id, new PriorityQueue(5)); PriorityQueue ss = scoreMap.get(s.id); ss.offer(s.score); if(ss.size() > 5) ss.poll(); } Map<Integer, Double> avgHighScore = new HashMap<Integer, Double>(); for(int id : scoreMap.keySet()){ PriorityQueue pq = scoreMap.get(id); double sum = 0; for(double s : pq) sum += s; avgHighScore.put(id, sum / 5); } return avgHighScore; }

Closest Two Sum

public static double[] find(double[] weights, double target){ if(weights == null || weights.length < 2) return null; Arrays. sort(weights); int i = 0, j = weights.length - 1; double[] ans = new double[2]; while(i < j){ if(weights[i] + weights[j] == target){ ans[0] = weights[i]; ans[1] = weights[j]; return ans; } else if(weights[i] + weights[j] < target){ ans[0] = weights[i]; ans[1] = weights[j]; i++; } else j--; } return j == 0? null : ans; } 要求在 array 中选出两个 weights 總总和小于等于 capacity 但最接近 capacity 然後指定到一個 Container object 並且 return public static ListNode reverseHalf(ListNode head){ ListNode dummy = new ListNode(-1); dummy.next = head; ListNode slow = dummy, fast = dummy.next; // find out middle node while(fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } dummy.next = null; fast = slow.next; slow.next = null; while(fast != null){ ListNode cur = fast; fast = fast.next; cur.next = slow.next; slow.next = cur; } return head; }

Reverse Half Linked List

Maze

  • 给个 array, 其中只有一格是 9 ,

LRU Cache

Miss

public static int countMissLL(int[] arr, int size){ if(arr == null || arr.length == 0) return 0; if(size < 1) return arr.length; LinkedList cache = new LinkedList(); int missed = 0; for(int x : arr){ if(cache.contains(x)) cache.remove(x); else missed++; cache.addFirst(x); if(cache.size() > size) cache.removeLast(); } return missed; } public static int countMiss(int[] arr, int size){ if(arr == null || arr.length == 0) return 0; if(size < 1) return arr.length; int missed = 0; LinkedHashMap<Integer, Boolean> cache = new LinkedHashMap<Integer, Boolean>(size, 0.75f, true){ @Override public boolean removeEldestEntry(Map.Entry<Integer, Boolean> eldest){ return this.size() > size; } }; for(int x : arr){ if(cache.get(x) == null){ missed++; cache.put(x, true); } } return missed; }

City Connection

public static ArrayList getLowCost(ArrayList connections) { if(connections == null || connections.isEmpty()) return connections; Collections. sort(connections, new Comparator(){ @Override public int compare(Connection c1, Connection c2){ return c1.cost - c2.cost; } }); Map<String, String> map = new HashMap<String, String>();// pre-processing to make city connect to itself for(Connection con : connections){ map.put(con.node1, con.node1); map.put(con.node2, con.node2); } ArrayList ans = new ArrayList(); // traverse connections to build MST for(Connection con : connections){ String root1 = root(con.node1, map); String root2 = root(con.node2, map); if(root1.equals(root2)) continue; // if they are already connected map.put(root2, root1); // union them ans.add(con); } if(map.size() - 1 != ans.size()) return null; // 检查是否联通,不连通的话边更少 Collections. sort(ans, new Comparator(){ @Override public int compare(Connection c1, Connection c2){ if(c1.node1.equals(c2.node1)) return c1.node2.compareTo(c2.node2); return c1.node1.compareTo(c2.node1); } }); return ans; }

Order Dependency

public static List getOrderList(List<Order_Dependency> orderDependencies){ Map<String, Order> orderMap = new HashMap<String, Order>(); Map<String, Integer> in_degree = new HashMap<String, Integer>(); Map<String, Set> graph = new HashMap<String, Set>(); for(Order_Dependency od : orderDependencies) { String order = od.order.name; String dept = od.dependent.name; orderMap.putIfAbsent(order, od.order); orderMap.putIfAbsent(dept, od.dependent); in_degree.putIfAbsent(order, 0); in_degree.putIfAbsent(dept, 0); if(!graph.containsKey(order) || !graph.get(order).contains(dept)) in_degree.put(dept, in_degree.get(dept) + 1); // duplicate dependencies would be ignored. graph.putIfAbsent(order, new HashSet()); graph.get(order).add(dept); } Queue que = new LinkedList(); for(String key : in_degree.keySet()) if(in_degree.get(key) == 0) que.offer(key); List ans = new ArrayList(); while(!que.isEmpty()) { String s = que.poll(); ans.add(orderMap.get(s)); Set adjs = graph.get(s); if(adjs == null) continue; for(String adj : adjs) if(in_degree.put(adj, in_degree.get(adj) - 1) == 1) que.offer(adj); } if(in_degree.size() != ans.size()) return null; return ans; }

Sliding Window Max

public static int[] maxSlidingWindow(int[] nums, int k) { if(nums == null || nums.length == 0 || k > nums.length) return new int[0]; if(k < 1) return nums; int len = nums.length; Deque dq = new LinkedList(); int[] ans = new int[len - k + 1]; for(int i = 0; i < len; i++) { while(!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) dq.pollLast(); dq.offerLast(i); if(dq.peekFirst() + k == i) dq.pollFirst(); if(i + 1 - k >= 0) ans[i+1-k] = nums[dq.peekFirst()]; } return ans; }

Gray Code

public static int check(byte a, byte b){ byte x = (byte) (a ^ b); int count = 0; while(x != 0){ count++; x = (byte) (x & (x- 1)); } return count == 1? 1 : 0; } public static int[] makeLargest(int a, int b, int c, int d) { int[] ans = new int[]{a, b, c, d}; Arrays. sort(ans); swap(ans, 0, 1); swap(ans, 2, 3); swap(ans, 0, 3); return ans; } public static void swap(int[] arr, int i, int j){ int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; }

Four

Integer

  • Given four integers, make F(S) = abs(S[0]-S[1])+abs(S[1]-S[2])+abs(S[2]-S[3]) to be largest. */ Given two hexadecimal numbers find if they can be consecutive in gray code For example: 10001000, 10001001 return 1 since they are successive in gray code Example2: 10001000, 10011001 return - since they are not successive in gray code.