剑指Offer刷题记录,共75题,目前尚有若干困难题未完成,先放一放
剑指 Offer(第 2 版) - 力扣(LeetCode)
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
public class Offer31 { public static void main(String[] args) { int[] pushed = {1,2,3,4,5}; int[] poped = {4,5,3,2,1};
System.out.println(validateStackSequences(pushed, poped)); } public static boolean validateStackSequences(int[] pushed, int[] popped){ if(pushed.length != popped.length){ return false; } if(pushed.length == 0){ return true; } if(pushed.length == 1){ return pushed[0] == popped[0]; } Stack<Integer> stack = new Stack<>(); int popindex = 0; int pushindex = 0; stack.push(pushed[pushindex++]); while(pushindex < pushed.length || popindex <popped.length){ if(stack.isEmpty()){ if(pushindex >= pushed.length){ return false; } stack.push(pushed[pushindex++]); } if(stack.peek() != popped[popindex]){ if(pushindex >= pushed.length){ return false; } stack.push(pushed[pushindex++]); }else { popindex++; stack.pop(); } } return true; } public boolean validateStackSequences2(int[] pushed, int[] popped) { Deque<Integer> stack = new ArrayDeque<Integer>(); int n = pushed.length; for (int i = 0, j = 0; i < n; i++) { stack.push(pushed[i]); while (!stack.isEmpty() && stack.peek() == popped[j]) { stack.pop(); j++; } } return stack.isEmpty(); } }
|
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
public class Offer32_1 { public static void main(String[] args) {
} public int[] levelOrder(TreeNode root) { if(root == null) return new int[]{}; Deque<TreeNode> treeNodes = new LinkedList<>(); treeNodes.add(root); int[] ans = new int[1000]; int temp = 0; while (!treeNodes.isEmpty()){ TreeNode out = treeNodes.pop(); if(out.left != null) treeNodes.add(out.left); if(out.right != null) treeNodes.add(out.right); ans[temp++] = out.val; } return Arrays.copyOfRange(ans,0,temp-1); } }
|
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
public class Offer32_2 { public List<List<Integer>> levelOrder(TreeNode root) { if(root==null)return new ArrayList<>(); int tempLayercount = 1; int nextLayercount = 0; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); List<List<Integer>> ans = new ArrayList<>(); List<Integer> innerans = new ArrayList<>(); while(!queue.isEmpty()){ TreeNode node = queue.poll(); innerans.add(node.val); if(node.left!=null) {queue.add(node.left);nextLayercount+=1;} if(node.right!=null) {queue.add(node.right);nextLayercount+=1;} tempLayercount -= 1; if(tempLayercount == 0){ tempLayercount = nextLayercount; if(!innerans.isEmpty()){ans.add(innerans);} innerans = new ArrayList<>(); nextLayercount = 0; } } if(!innerans.isEmpty()){ans.add(innerans);} return ans; } }
|
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
public class Offer32_3 { public List<List<Integer>> levelOrder(TreeNode root) { if(root==null)return new ArrayList<>(); int tempLayercount = 1; int nextLayercount = 0; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); List<List<Integer>> ans = new ArrayList<>(); List<Integer> innerans = new ArrayList<>(); int countlevel = 0; while(!queue.isEmpty()){ TreeNode node = queue.poll(); innerans.add(node.val); if(node.left!=null) {queue.add(node.left);nextLayercount+=1;} if(node.right!=null) {queue.add(node.right);nextLayercount+=1;} tempLayercount -= 1; if(tempLayercount == 0){ tempLayercount = nextLayercount; countlevel ++; if(!innerans.isEmpty()){ if(countlevel %2 == 1){ ans.add(innerans); }else { Collections.reverse(innerans); ans.add(innerans); }
} innerans = new ArrayList<>(); nextLayercount = 0; } } if(!innerans.isEmpty()){ans.add(innerans);} return ans; }
}
|
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true
,否则返回 false
。假设输入的数组的任意两个数字都互不相同。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
public class Offer33 { public static void main(String[] args) { int[] input = {1,3,2,6,5}; System.out.println(verifyPostorder(input)); } public static boolean verifyPostorder(int[] postorder) { return verifyhelper(postorder,0,postorder.length-1); } public static boolean verifyhelper(int[] postorder,int start,int end){ if(start >= end){ return true; } boolean flagFirst = true; int mid = start; int midout = start; int rootval = postorder[end]; while(mid < end){ if(postorder[mid] > rootval){ if(flagFirst){ midout = mid; } flagFirst = false; mid++; }else if(postorder[mid] < rootval && flagFirst){ mid++; }else { return false; } } return verifyhelper(postorder,start,midout-1)&&verifyhelper(postorder,midout,end-1); } }
|
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
public class Offer34 { public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); System.out.println(pathSum(root, 3)); } static int sum = 0; static LinkedList<Integer> innerans = new LinkedList<>(); static List<List<Integer>> ans = new ArrayList<>();
public static List<List<Integer>> pathSum(TreeNode root, int target) { ans.clear(); innerans.clear(); if(root == null) return new ArrayList<>(); pathSumHelper(root,target); return ans; } public static void pathSumHelper(TreeNode root, int target){ sum += root.val; innerans.add(root.val); if(root.right != null || root.left != null){ if(root.right !=null){ pathSumHelper(root.right,target); } if(root.left != null){ pathSumHelper(root.left,target); } sum -= root.val; innerans.removeLast(); }else { if(sum == target){ ans.add(new LinkedList<Integer>(innerans)); } sum -= root.val; innerans.removeLast(); } } }
|
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
public class Offer35 { public static void main(String[] args) {
} Map<Node, Node> cachedNode = new HashMap<Node, Node>(); public Node copyRandomList(Node head) { if(head == null) return null;
if (!cachedNode.containsKey(head)){ Node dummy = new Node(head.val); cachedNode.put(head,dummy); dummy.next = copyRandomList(head.next); dummy.random = copyRandomList(head.random); } return cachedNode.get(head); } }
|
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
public class Offer36 { TreeNode pre, head; public TreeNode treeToDoublyList(TreeNode root) { if(root == null) return null; dfs(root); head.left = pre; pre.right = head; return head; } void dfs(TreeNode cur) { if(cur == null) return; dfs(cur.left); if(pre != null) pre.right = cur; else head = cur; cur.left = pre; pre = cur; dfs(cur.right); } }
|
请实现两个函数,分别用来序列化和反序列化二叉树。
你需要设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
提示:输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
public class Offer37_2 { public static void main(String[] args) { String input ="1 2 3 null null 4 5 null null null null"; TreeNode out = deserialize(input); System.out.println("finished"); System.out.println(serialize(out)); } public static String serialize(TreeNode root) { if(root == null){ return "null "; } StringBuilder sb = new StringBuilder(); Deque<TreeNode> treeNodes = new LinkedList<>(); treeNodes.add(root); while (!treeNodes.isEmpty()){ TreeNode temp = treeNodes.pop(); if(temp == null){ sb.append("null "); continue; } sb.append(temp.val); sb.append(" "); if(temp.left != null){ treeNodes.add(temp.left); }else { treeNodes.add(null); } if(temp.right != null){ treeNodes.add(temp.right); }else { treeNodes.add(null); }
} return sb.toString(); }
public static TreeNode deserialize(String data) { if(data.equals("null ")){ return null; } String[] dataqueue = data.split(" "); TreeNode root = new TreeNode(Integer.parseInt(dataqueue[0])); Deque<TreeNode> treeNodes = new LinkedList<>(); treeNodes.add(root);
TreeNode fatherNode = treeNodes.peek(); TreeNode tempNode = null; for(int i = 1;i<dataqueue.length;i++){ fatherNode = treeNodes.peek(); if(dataqueue[i].equals("null") ){ if((i+1) %2 == 0){ fatherNode.left = null; }else { fatherNode.right = null; treeNodes.pop(); } continue; } tempNode = new TreeNode(Integer.parseInt(dataqueue[i])); if((i+1) %2 == 0){ fatherNode.left = tempNode; treeNodes.add(tempNode); }else { fatherNode.right = tempNode; treeNodes.add(tempNode); treeNodes.pop(); } } return root; } }
|
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
public class Offer38 { public static void main(String[] args) { String input = "aab"; System.out.println(Arrays.toString(permutation(input))); }
public static String[] permutation(String s) {
if(s.length() == 1) return new String[]{s}; HashSet<String> ans = new HashSet<>(); for(int i = 0;i<s.length();i++){ String temp = String.valueOf(s.charAt(i)); String newString = s.replaceFirst(temp,""); String[] thistime = permutation(newString); for (String item:thistime){ StringBuilder stringBuilder = new StringBuilder(item); stringBuilder.append(temp); ans.add(stringBuilder.toString()); } } String[] re = new String[ans.size()]; int i = 0; for(String x:ans){ re[i++] = x; } return re; } }
|
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
public class Offer39 { public static void main(String[] args) { int[] inputs = {1, 2, 3, 2, 2, 2, 5, 4, 2}; System.out.println(majorityElement(inputs)); } public static int majorityElement(int[] nums) { int count = 0; int target = nums[0]; for(int item:nums){ if(count == 0){ target = item; } if(item == target){ count +=1; }else{ count -=1; } } return target; } }
|
输入整数数组 arr
,找出其中最小的 k
个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public class Offer40 { public int[] getLeastNumbers(int[] arr, int k) { PriorityQueue<Integer> queue = new PriorityQueue<>(); for(int x:arr){ queue.add(x); } int[] ans = new int[k]; for(int i = 0;i<k;i++){ ans[i] = queue.poll(); } return ans; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class MedianFinder { PriorityQueue<Integer> maxQueue; PriorityQueue<Integer> minQueue; public MedianFinder() { maxQueue = new PriorityQueue<>(); minQueue = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); }
public void addNum(int num) { if(minQueue.size() == 0){ minQueue.add(num); return;} if(maxQueue.size() == 0 && num > minQueue.peek()){ maxQueue.add(num); return; } if(num > minQueue.peek()){ maxQueue.add(num); if(maxQueue.size() != minQueue.size()){ minQueue.add(maxQueue.poll()); } }else { minQueue.add(num); if(minQueue.size() != maxQueue.size()+1){ maxQueue.add(minQueue.poll()); } } }
public double findMedian() { if(minQueue.size() > maxQueue.size()){ return (double) minQueue.peek(); }else { return ((double) minQueue.peek()+maxQueue.peek())/2; } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
public class Offer42 { public static void main(String[] args) { int[] inputs = {-2,1,-3,4,-1,2,1,-5,4}; System.out.println(maxSubArray(inputs)); } public static int maxSubArray(int[] nums) { int temp = nums[0]; int max = Math.max(Integer.MIN_VALUE,temp); for(int i = 1;i<nums.length;i++){ if(temp<0){ temp = nums[i]; }else { temp = nums[i]+temp; } max = Math.max(temp,max); } return max; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
public class Offer44 { public int findNthDigit(int n) { int d = 1, count = 9; while (n > (long) d * count) { n -= d * count; d++; count *= 10; } int index = n - 1; int start = (int) Math.pow(10, d - 1); int num = start + index / d; int digitIndex = index % d; int digit = (num / (int)(Math.pow(10, d - digitIndex - 1))) % 10; return digit; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public class Offer50 { public char firstUniqChar(String s) { int[] count = new int[26]; char[] chars = s.toCharArray(); for (char c : chars) count[c - 'a']++; for (char c : chars) { if (count[c - 'a'] == 1) return c; } return ' '; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public class Offer52 { ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } ListNode pA = headA, pB = headB; while (pA != pB) { pA = pA == null ? headB : pA.next; pB = pB == null ? headA : pB.next; } return pA; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class Offer53_1 { public static void main(String[] args) { int[] inputs = {5,7,7,8,8,10}; System.out.println(search(inputs, 8)); } public static int search(int[] nums, int target) { int count = 0; for(int x:nums){ if(x > target){ break; }else if(x == target){ count++; } } return count; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
public class Offer53_2 { public static void main(String[] args) { int[] inputs = {1}; System.out.println(missingNumber(inputs)); } public static int missingNumber(int[] nums) { int l = 0, h = nums.length-1, m = (l+h)/2;
while (l <= h) { if (m != nums[m]) { h = m-1; } else { l = m+1; } m = (l+h)/2; } return l; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| import java.util.Deque; import java.util.LinkedList; import java.util.PriorityQueue;
import static com.jianzhioffer.Offer37_2.deserialize;
public class Offer54 { public static void main(String[] args) { String input ="5 3 6 2 4 null null 1"; TreeNode out = deserialize(input); System.out.println(kthLargest2(out,3)); } public int kthLargest(TreeNode root, int k) { PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((o1, o2) -> o2 - o1); Deque<TreeNode> treeNodeDeque = new LinkedList<>(); treeNodeDeque.add(root); while (!treeNodeDeque.isEmpty()){ TreeNode temp = treeNodeDeque.pop(); priorityQueue.add(temp.val); if(temp.left != null){ treeNodeDeque.add(temp.left); } if(temp.right != null){ treeNodeDeque.add(temp.right); } } while (k>1){ priorityQueue.poll(); k --; } return priorityQueue.poll(); } public static int kthLargest2(TreeNode root, int k) { lastrank(root,k); int re = ranked.getLast(); ranked.clear(); return re; } static LinkedList<Integer> ranked = new LinkedList<>(); public static void lastrank(TreeNode root,int k){ if(root == null) return; lastrank(root.right,k); if(ranked.size() == k) return; ranked.add(root.val); lastrank(root.left,k); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public class Offer55_1 { public static void main(String[] args) { String input ="5 3 6 2 4 null null 1"; TreeNode out = deserialize(input); System.out.println(maxDepth(out)); } public static int maxDepth(TreeNode root) { return findMaxDepth(root,0); } public static int findMaxDepth(TreeNode node,int layer){ if(node != null){ layer +=1; }else return layer; return Math.max(findMaxDepth(node.left,layer),findMaxDepth(node.right,layer)); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
public class Offer55_2new { public boolean isBalanced(TreeNode root) { if (root == null) { return true; } else { return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right); } }
public int height(TreeNode root) { if (root == null) { return 0; } else { return Math.max(height(root.left), height(root.right)) + 1; } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import static com.jianzhioffer.Offer37_2.deserialize;
public class Offer55_2 { public static void main(String[] args) { String input ="1 2 2 3 3 3 3 4 4 4 4 4 4 null null 5 5"; TreeNode out = deserialize(input); System.out.println(isBalanced(out)); } public static boolean isBalanced(TreeNode root) { if(root == null) return true; return balanceHelper(root,0,0); } static int min = Integer.MAX_VALUE; public static boolean balanceHelper(TreeNode node,int temp,int max){ if(max - min >=2) return false; if(node.right == null || node.left == null) { min = Math.min(min,temp); } if(node.right == null && node.left == null){ return max - min < 2; } boolean right = true; boolean left = true; if(node.right != null){ right = balanceHelper(node.right,temp+1,max+1); } if(node.left != null){ left = balanceHelper(node.left,temp+1,max+1); } return right&&left; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class Offer57_1 { public static void main(String[] args) { int[] inputs = {10,26,30,31,47,60}; System.out.println(Arrays.toString(twoSum(inputs, 40))); } public static int[] twoSum(int[] nums, int target) { HashSet<Integer> set = new HashSet<>(); for(int x:nums){ if(set.contains(x)){ return new int[]{x,target-x}; }else { set.add(target-x); } } return null; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
public class Offer57_2 { public static void main(String[] args) { int[] inputs = {10,26,30,31,47,60}; System.out.println(Arrays.toString(findContinuousSequence(9))); } public static int[][] findContinuousSequence(int target) { List<Integer[]> ans = new ArrayList<>(); int sum = 0; for(int i = 1;i<=target/2;i++){ sum = i; for(int j = i+1;j<=target/2+1;j++){ sum+=j; if(sum == target){ Integer[] innerans = new Integer[j-i+1]; for(int u = 0;u<innerans.length;u++){ innerans[u] = i+u; } ans.add(innerans); }else if(sum > target){ break; } } } int[][] re = new int[ans.size()][]; int z= 0; for(Integer[] x:ans){ re[z++] = Arrays.stream(x).mapToInt(Integer::valueOf).toArray(); } return re; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public class Offer58_1 { public static void main(String[] args) { String input = "a good example"; System.out.println(reverseWords(input)); } public static String reverseWords(String s) { s = s.trim(); String[] sString = s.split(" "); StringBuilder sb = new StringBuilder(); for(int i = sString.length-1;i>=0;i--){ if(sString[i].equals("")) continue; sb.append(sString[i]+" "); } return sb.toString().trim(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public class Offer58_2 { public static void main(String[] args) { String s = "abcdefg"; System.out.println(reverseLeftWords(s, 2)); } public static String reverseLeftWords(String s, int n) { StringBuilder sb = new StringBuilder(s.substring(n)); sb.append(s.substring(0,n)); return sb.toString(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
public class Offer61 { public static void main(String[] args) {
int[] inputs = {9,0,6,0,10}; System.out.println(isStraight(inputs)); } public static boolean isStraight(int[] nums) { Arrays.sort(nums); int count = 0; for(int x:nums){ count = x == 0 ? count+1:count; } if(count == 5)return true; int former = nums[count]; for(int i = count+1;i<nums.length;i++){ if(nums[i] == former+1){ former = nums[i]; }else if(nums[i] == former){ return false; }else if(count>0) { count = count - (nums[i] - former)+1; if (count < 0) { return false; } former = nums[i]; }else { return false; } } return true; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
public class Offer62 { public static void main(String[] args) {
} public int lastRemaining(int n, int m) { int f = 0; for (int i = 2; i != n + 1; ++i) { f = (m + f) % i; } return f; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
public class Offer63 { public static void main(String[] args) { int[] input = {5,6}; System.out.println(getMaxDiff(input, 2)); } public static int getMaxDiff(int[] A, int n) { int max_diff = 0; int min_val = A[0]; for (int i = 1; i < n; i++) { int diff = A[i] - min_val; max_diff = Math.max(max_diff, diff); min_val = Math.min(min_val, A[i]); } return max_diff; } public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true; }
ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; }
Stack<Integer> stack = new Stack<>(); ListNode cur = slow.next; while (cur != null) { stack.push(cur.val); cur = cur.next; }
cur = head; while (!stack.isEmpty()) { if (cur.val != stack.pop()) { return false; } cur = cur.next; }
return true; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
public class Offer65 { public int add(int a, int b) { while (b != 0) { int carry = (a & b) << 1; a = a ^ b; b = carry; } return a; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class Offer68_1 { public static void main(String[] args) {
} public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val > p.val && root.val > q.val){ return lowestCommonAncestor(root.left,p,q); }else if(root.val < p.val && root.val < q.val){ return lowestCommonAncestor(root.right,p,q); }else { return root; } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
public class Offer68_2 { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null){ return null; }
if(root.val == q.val){ return q;
}else if(root.val == p.val){ return p; }else {
TreeNode left = lowestCommonAncestor(root.left,p,q); TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left != null && right != null){ return root;
}else if(left == null){ return right; }else {
return left; } } } }
|