1. Two Sum
第36行本来应该是if (nodes.get(left).key < nodes.get(right).key) { 一不小心误写成了if (nodes.get(left).key < nodes.get(right).value) { 竟然A了!!!!
1 class Node{ 2 int key; 3 int value; 4 public Node(int key, int value) { 5 this.key = key; 6 this.value = value; 7 } 8 } 9 public class Solution { 10 /* 11 * @param numbers : An array of Integer 12 * @param target : target = numbers[index1] + numbers[index2] 13 * @return : [index1 + 1, index2 + 1] (index1 < index2) 14 */ 15 public int[] twoSum(int[] numbers, int target) { 16 if (numbers == null || numbers.length <= 1) { 17 return new int [2]; 18 } 19 //put the key and value in list, the type of list is Node 20 List<Node> nodes = new ArrayList<>(); 21 for (int i = 0; i < numbers.length; i++) { 22 nodes.add(new Node(i, numbers[i])); 23 } 24 //sort the list 25 Collections.sort(nodes, new Comparator<Node>() { 26 public int compare(Node a, Node b) { 27 return a.value - b.value; 28 } 29 }); 30 // Two points 31 int left = 0; 32 int right = numbers.length - 1; 33 int[] result = new int[2]; 34 while (left < right) { 35 if (nodes.get(left).value + nodes.get(right).value == target) { 36 if (nodes.get(left).key < nodes.get(right).value) { //第二个明显应该是key,但是第一次不小心写成了value,居然A了,但是lintcode却不能A 37 result[0] = nodes.get(left).key; 38 result[1] = nodes.get(right).key; 39 } else { 40 result[0] = nodes.get(right).key; 41 result[1] = nodes.get(left).key; 42 } 43 return result; 44 } else if (nodes.get(left).value + nodes.get(right).value < target) { 45 left++; 46 } else { 47 right--; 48 } 49 } 50 return result; 51 } 52 }
572. Subtree of Another Tree
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isSubtree(TreeNode root1, TreeNode root2) { 12 //如果root2不进行判断,也A了,但是很明显这样是错的 13 //这样的话并没有考虑,两个都为空,以及root1不为空,而root2为空的情况 14 if (root2 == null) { 15 return true; 16 } 17 if (root1 == null) { 18 return false; 19 } 20 if(isEqual(root1, root2)) { 21 return true; 22 } 23 return isSubtree(root1.left, root2) || isSubtree(root1.right, root2); 24 } 25 public boolean isEqual(TreeNode root1, TreeNode root2) { 26 if (root1 == null || root2 == null) { 27 return root1 == root2; 28 } 29 if (root1.val != root2.val) { 30 return false; 31 } 32 return isEqual(root1.left, root2.left) && isEqual(root1.right, root2.right); 33 } 34 }