数组中重复的数字

题目描述:在一个长度为n的数组里面的所有数字都在0~n-1的范围内。数组中某些数字是重复的,但是不知道有几个数字重复了,也不知道每个数字重复了几次,请找出数组中任意一个重复的数字。例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3.

解题思路:

1.先把输入的数组排序,从排序的数组中找出重复的数字是一件很容易的事,只需从头到尾扫描排序后的数组就可以了。排序一个长度为n的数组需要O(nlogn)的时间。

2.可以利用哈希表来解决,从头到尾按顺序扫描数组的每个数字,每扫描到一个数字的时候,都可以用O(1)的时间判断哈希表里面是否已经包含了该数字。如果哈希表里面还没有这个数字,就把他加入哈希表,如果已经存在了该数字,就找到一个重复的数字,算法的时间复杂度是O(n),空间复杂度为O(n),

3.假设重排这个数组,如果数组中没有重复的数字,那么当数组排序后,数字i将出现在下标为i的位置。由于数组中有重复的数字,那有些位置可能存在多个数字,有些位置可能没有数字。

现在重排这个数组,从头打到尾依次扫描这个数组中的每个数字。当扫描到下标为i的数字时,首先比较这个数字m是不是等于i,如果是,则接着扫描下一个数字;如果不是,那么拿它和第m个数字进行比较。如果它和第m个数字相等,就找到了一个重复的数字;如果它和第m个数字不相等,就把第i个数字和第m个数字交换,把m放在属于它的位置,接下来重复这个比较交换的过程,直到发现第一个重复数字。

以 (2, 3, 1, 0, 2, 5) 为例:

  1. position-0 : (2,3,1,0,2,5) // 2 <-> 1
  2. (1,3,2,0,2,5) // 1 <-> 3
  3. (3,1,2,0,2,5) // 3 <-> 0
  4. (0,1,2,3,2,5) // already in position
  5. position-1 : (0,1,2,3,2,5) // already in position
  6. position-2 : (0,1,2,3,2,5) // already in position
  7. position-3 : (0,1,2,3,2,5) // already in position
  8. position-4 : (0,1,2,3,2,5) // nums[i] == nums[nums[i]], exit

遍历到位置 4 时,该位置上的数为 2,但是第 2 个位置上已经有一个 2 的值了,因此可以知道 2 重复。

例题:

  1. 题目描述
  2. 在一个长度为n的数组里的所有数字都在0n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2
  1. public class Solution {
  2. // Parameters:
  3. // numbers: an array of integers
  4. // length: the length of array numbers
  5. // duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
  6. // Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
  7. // 这里要特别注意~返回任意重复的一个,赋值duplication[0]
  8. // Return value: true if the input is valid, and there are some duplications in the array number
  9. // otherwise false
  10. public boolean duplicate(int numbers[],int length,int [] duplication) {
  11. if (numbers == null || numbers.length == 0) {
  12. return false;
  13. }
  14. for (int i = 0; i < length; i++) {
  15. while (numbers[i] != i) {
  16. if (numbers[i] == numbers[numbers[i]]) {
  17. duplication[0] = numbers[i];
  18. return true;
  19. }
  20. swap(numbers, i, numbers[i]);
  21. }
  22. }
  23. return false;
  24. }
  25. public void swap(int[] numbers, int i, int j) {
  26. int temp = numbers[i];
  27. numbers[i] = numbers[j];
  28. numbers[j] = temp;
  29. }
  30. }

-----------------------------------------------------------------------

不修改数组找出重复的数字

题目描述:在一个长度为n+1的数组里面的所有数字都在1~n的范围内,所以数组中至少有一个数字是重复的,请找出数组当中任意一个重复的数字,但不能修改输入的数组。例如输入长度为8的数组{2,3,5,4,3,2,6,7},那么对应的输出是重复的数字2或者3。

解题思路:

1.可以创建一个长度为n+1上午辅助数组,然后逐一把原数组的每个数字复制到辅助数组。如果原数组中被复制的数字是m,则把它复制到辅助数组中下标为m的位置,这样很容易就能发现哪个数字是重复的,这样需要O(n)的辅助空间。

2.可以把1~n的数字从中间的数字m分为两部分,前面一半为1~m,后面一半为m+1~n。如果1~m的数字的数目超过m,那么这一版的区间里面一定包含重复数字,否则另一半区间里面肯定包含重复数字。我们可以继续吧包含重复数字的区间一分为二,直到找到一个重复的数字,类似二分法。

例题:

  1. 633. 寻找重复的数
  2. 给出一个数组 nums 包含 n + 1 个整数,每个整数是从 1 n (包括边界),保证至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
  3.  
  4. 样例
  5. 给出 nums = [5,5,4,3,2,1],返回 5.
  6. 给出 nums = [5,4,4,3,2,1],返回 4.
  7.  
  8. 注意事项
  9. 1.不能修改数组(假设数组只能读)
  10. 2.只能用额外的O(1)的空间
  11. 3.时间复杂度小于O(n^2)
  12. 4.数组中只有一个重复的数,但可能重复超过一次

解法:

  1. public class Solution {
  2. /**
  3. * @param nums: an array containing n + 1 integers which is between 1 and n
  4. * @return: the duplicate one
  5. */
  6. public int findDuplicate(int[] nums) {
  7. // write your code here
  8. if (nums == null || nums.length == 0) {
  9. return -1;
  10. }
  11. int start = 1;
  12. int end = nums.length - 1;
  13. while (end >= start) {
  14. int mid = ((end - start) >> 1) + start;
  15. int count = countRange(nums, start, mid);
  16. if (end == start) {
  17. if (count > 1) {
  18. return start;
  19. } else {
  20. break;
  21. }
  22. }
  23. //前半部分数字在数组中出现的次数大于前半部分数字的个数
  24. if (count > (mid - start + 1)) {
  25. end = mid;
  26. } else {
  27. start = mid + 1;
  28. }
  29. }
  30. return -1;
  31. }
  32. /**
  33. * 统计nums数组中某个范围当中的数字出现的次数
  34. **/
  35. public int countRange(int[] nums, int start, int end) {
  36. if (nums == null || nums.length == 0) {
  37. return 0;
  38. }
  39. int count = 0;
  40. for (int i = 0; i < nums.length; i++) {
  41. if (nums[i] >= start && nums[i] <= end) {
  42. count++;
  43. }
  44. }
  45. return count;
  46. }
  47. }

-------------------------------------------------------------------------------------

二维数组中的查找

  1. 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
    请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
  1. Consider the following matrix:
  2. [
  3. [1, 4, 7, 11, 15],
  4. [2, 5, 8, 12, 19],
  5. [3, 6, 9, 16, 22],
  6. [10, 13, 14, 17, 24],
  7. [18, 21, 23, 26, 30]
  8. ]
  9.  
  10. Given target = 5, return true.
  11. Given target = 20, return false.
  1. public class Solution {
  2. /**
  3. * 从左下角开始查找,复杂度:O(M + N) + O(1)
  4. **/
  5. public boolean Find(int target, int [][] array) {
  6. if (array == null || array.length == 0 || array[0] == null || array[0].length == 0) {
  7. return false;
  8. }
  9. int row = array.length;
  10. int col = array[0].length;
  11. int i = row - 1;
  12. int j = 0;
  13. while (i >= 0 && j < col) {
  14. if (target == array[i][j]) {
  15. return true;
  16. } else if (target > array[i][j]) {
  17. j++;
  18. } else {
  19. i--;
  20. }
  21. }
  22. return false;
  23.  
  24. }
  25. }

-------------------------------------------

替换空格

  1. 题目描述
  2. 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
  1. 解题思路
  2. 在字符串尾部填充任意字符,使得字符串的长度等于替换之后的长度。因为一个空格要替换成三个字符(%20),因此当遍历到一个空格时,需要在尾部填充两个任意字符。
  3.  
  4. P1 指向字符串原来的末尾位置,P2 指向字符串现在的末尾位置。P1 P2从后向前遍历,当 P1 遍历到一个空格时,就需要令 P2 指向的位置依次填充 02%(注意是逆序的),否则就填充上 P1 指向字符的值。
  5.  
  6. 从后向前遍是为了在改变 P2 所指向的内容时,不会影响到 P1 遍历原来字符串的内容。
  1. public class Solution {
  2. public String replaceSpace(StringBuffer str) {
  3. int oldLen = str.length() - 1;
  4. for (int i = 0; i < oldLen + 1; i++) {
  5. if (str.charAt(i) == ' ') {
  6. str.append(" ");
  7. }
  8. }
  9. int newLen = str.length() - 1;
  10. while (oldLen >= 0 && newLen > oldLen) {
  11. char temp = str.charAt(oldLen--);
  12. if (temp == ' ') {
  13. str.setCharAt(newLen--, '0');
  14. str.setCharAt(newLen--, '2');
  15. str.setCharAt(newLen--, '%');
  16. } else {
  17. str.setCharAt(newLen--, temp);
  18. }
  19. }
  20. return str.toString();
  21. }
  22. }

--------------------------------------------------------------------

从头到尾打印链表

  1. 题目描述
  2. 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
  1. /**
  2. * public class ListNode {
  3. * int val;
  4. * ListNode next = null;
  5. *
  6. * ListNode(int val) {
  7. * this.val = val;
  8. * }
  9. * }
  10. *
  11. */
  12. import java.util.ArrayList;
  13. import java.util.Stack;
  14. public class Solution {
  15. //使用栈
  16. public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
  17. Stack<Integer> stack = new Stack<>();
  18. while (listNode != null) {
  19. stack.push(listNode.val);
  20. listNode = listNode.next;
  21. }
  22. ArrayList<Integer> res = new ArrayList<>();
  23. while (!stack.isEmpty()) {
  24. res.add(stack.pop());
  25. }
  26. return res;
  27. }
  28. }

-----------------------------------------------------------------------------------------

重建二叉树

根据前序遍历和中序遍历重建二叉树

  1. 题目描述
  2. 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
    例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
  1. 解题思路
  2. 前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。
  3. 递归的调用,实现功能。
  1. /**
  2. * Definition for binary tree
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. import java.util.Map;
  11. import java.util.HashMap;
  12. public class Solution {
  13. public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
  14. Map<Integer, Integer> map = new HashMap<>();
  15. for (int i = 0; i < in.length; i++) {
  16. map.put(in[i], i);
  17. }
  18. TreeNode root = helper(pre, 0, pre.length - 1, in, 0, in.length - 1, map);
  19. return root;
  20. }
  21. public TreeNode helper(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd, Map<Integer, Integer> inMap) {
  22. if (preStart > preEnd || inStart > inEnd) {
  23. return null;
  24. }
  25. TreeNode root = new TreeNode(pre[preStart]);
  26. int index = inMap.get(root.val);
  27. int leftNums = index - inStart;
  28. root.left = helper(pre, preStart + 1, preStart + leftNums, in, inStart, index - 1, inMap);
  29. root.right = helper(pre, preStart + leftNums + 1, preEnd, in, index + 1, inEnd, inMap);
  30. return root;
  31. }
  32. }

根据后序遍历和中序遍历重建二叉树

106. Construct Binary Tree from Inorder and Postorder Traversal

  1. Given inorder and postorder traversal of a tree, construct the binary tree.
  2.  
  3. Note:
  4. You may assume that duplicates do not exist in the tree.
  5.  
  6. For example, given
  7.  
  8. inorder = [9,3,15,20,7]
  9. postorder = [9,15,7,20,3]
  10. Return the following binary tree:
  11.  
  12. 3
  13. / \
  14. 9 20
  15. / \
  16. 15 7
  1. 解题思路
  2. 后序遍历的最后一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。
  3. 递归的调用,实现功能。
  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. class Solution {
  11. public TreeNode buildTree(int[] inorder, int[] postorder) {
  12. if (inorder == null || postorder == null || inorder.length != postorder.length) {
  13. return null;
  14. }
  15. Map<Integer, Integer> map = new HashMap<>();
  16. for (int i = 0; i < inorder.length; i++) {
  17. map.put(inorder[i], i);
  18. }
  19. TreeNode root = helper(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, map);
  20. return root;
  21. }
  22. public TreeNode helper(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd, Map<Integer, Integer> map) {
  23. if (inStart > inEnd || postStart > postEnd) {
  24. return null;
  25. }
  26. TreeNode root = new TreeNode(postorder[postEnd]);
  27. int index = map.get(root.val);
  28. int leftNums = index - inStart;
  29. root.left = helper(inorder, inStart, index - 1, postorder, postStart, postStart + leftNums - 1, map);
  30. root.right = helper(inorder, index + 1, inEnd, postorder, postStart + leftNums, postEnd - 1, map);
  31. return root;
  32. }
  33. }

----------------------------------------------------------------

二叉树的下一个节点

  1. 题目描述
  2. 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

解题思路

① 如果一个节点的右子树不为空,那么该节点的下一个节点是右子树的最左节点;

② 否则,向上找第一个左链接指向的树包含该节点的祖先节点。

 
  1. /*
  2. public class TreeLinkNode {
  3. int val;
  4. TreeLinkNode left = null;
  5. TreeLinkNode right = null;
  6. TreeLinkNode next = null;
  7.  
  8. TreeLinkNode(int val) {
  9. this.val = val;
  10. }
  11. }
  12. */
  13. public class Solution {
  14. public TreeLinkNode GetNext(TreeLinkNode pNode)
  15. {
  16. if (pNode == null) {
  17. return null;
  18. }
  19. if (pNode.right != null) {
  20. TreeLinkNode node = pNode.right;
  21. while (node.left != null) {
  22. node = node.left;
  23. }
  24. return node;
  25. } else {
  26. while (pNode.next != null) {
  27. TreeLinkNode p = pNode.next;
  28. if (p.left == pNode) {
  29. return p;
  30. }
  31. pNode = pNode.next;
  32. }
  33. }
  34. return null;
  35. }
  36. }

----------------------------------------------------------------------------------------------------------

两个栈实现队列

  1. 题目描述
  2. 用两个栈来实现一个队列,完成队列的PushPop操作。 队列中的元素为int类型。
  1. 解题思路:
  2. 声明两个栈,stack1,stack2
  3. 进入队列的时候,都pushstack1
  4. 从队列中出去的时候,从stack2pop,如果stack2为空,
  5. 那么将stack1中的元素pop后压入stack2中,如果stack2还是为空,
  6. 那么抛出异常。
  1.  
  1. import java.util.Stack;
  2.  
  3. public class Solution {
  4. Stack<Integer> stack1 = new Stack<Integer>();
  5. Stack<Integer> stack2 = new Stack<Integer>();
  6.  
  7. public void push(int node) {
  8. stack1.push(node);
  9. }
  10.  
  11. public int pop() throws Exception{
  12. if (stack2.isEmpty()) {
  13. while (!stack1.isEmpty()) {
  14. stack2.push(stack1.pop());
  15. }
  16. }
  17. if (stack2.isEmpty()) {
  18. throw new Exception("queue is empty");
  19. }
  20. return stack2.pop();
  21.  
  22. }
  23. }

-----------------------------------------------------------------------------

两个队列实现栈

  1. import java.util.ArrayDeque;
  2. import java.util.Queue;
  3.  
  4. public class Demo08 {
  5. Queue<Integer> queue1 = new ArrayDeque<>();
  6. Queue<Integer> queue2 = new ArrayDeque<>();
  7.  
  8. public void push(int node) {
  9. //两个栈都为空时,优先考虑queue1
  10. if (queue1.isEmpty()&&queue2.isEmpty()) {
  11. queue1.add(node);
  12. return;
  13. }
  14.  
  15. //如果queue1为空,queue2有元素,直接放入queue2
  16. if (queue1.isEmpty()) {
  17. queue2.add(node);
  18. return;
  19. }
  20.  
  21. if (queue2.isEmpty()) {
  22. queue1.add(node);
  23. return;
  24. }
  25.  
  26. }
  27.  
  28. public int pop() {
  29. //两个栈都为空时,没有元素可以弹出
  30. if (queue1.isEmpty()&&queue2.isEmpty()) {
  31. try {
  32. throw new Exception("stack is empty");
  33. } catch (Exception e) {
  34. }
  35. }
  36. //如果queue1为空,queue2有元素, 将queue2的元素依次放入queue1中,直到最后一个元素,我们弹出。
  37. if (queue1.isEmpty()) {
  38. while (queue2.size()>1) {
  39. queue1.add(queue2.poll());
  40. }
  41. return queue2.poll();
  42. }
  43.  
  44. if (queue2.isEmpty()) {
  45. while (queue1.size()>1) {
  46. queue2.add(queue1.poll());
  47. }
  48. return queue1.poll();
  49. }
  50.  
  51. return (Integer) null;
  52. }
  53.  
  54. public static void main(String[] args) {
  55. Demo08 demo08 = new Demo08();
  56. demo08.push(1);
  57. demo08.push(2);
  58. demo08.push(3);
  59. demo08.push(4);
  60. System.out.println(demo08.pop());
  61. System.out.println(demo08.pop());
  62. demo08.push(5);
  63. System.out.println(demo08.pop());
  64. System.out.println(demo08.pop());
  65. System.out.println(demo08.pop());
  66. }
  67. }

-----------------------------------------------------------------------------------

菲波那切数列

  1. 题目描述
  2. 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
  3. n<=39

递归解法:

  1. public class Solution {
  2. public int Fibonacci(int n) {
  3. if (n <= 1) {
  4. return n;
  5. }
  6. int[] f = new int[n + 1];
  7. f[1] = 1;
  8. for (int i = 2; i <= n; i++) {
  9. f[i] = f[i - 1] + f[i - 2];
  10. }
  11. return f[n];
  12.  
  13. }
  14. }

非递归解法:

  1. public class Solution {
  2. public int Fibonacci(int n) {
  3. if (n <= 1) {
  4. return n;
  5. }
  6. //考虑到第 i 项只与第 i-1 和第 i-2 项有关,
  7. //因此只需要存储前两项的值就能求解第 i 项,
  8. //从而将空间复杂度由 O(N) 降低为 O(1)。
  9. int pre = 0;
  10. int p = 1;
  11. int res = 0;
  12. for (int i = 2; i <= n; i++) {
  13. res = pre + p;
  14. pre = p;
  15. p = res;
  16. }
  17. return res;
  18.  
  19. }
  20. }

-----------------------------------------------------------------------------

青蛙跳台阶

  1. 题目描述
  2. 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
  1. 解题思路:
  2. 首先考虑最简答的情况,如果只有一级台阶,那么只有一种跳法
  3. 如果有两级台阶,那么就有两种跳法
  4. 我们把n级台阶时的跳法看成n的函数,即为f(n),
  5. n>2时,第一次跳的时候就有两种不同的选择:
  6. 第一种是第一次只跳一级,此时跳法数目等于后面剩下的n-1级台阶的跳法数目,即为f(n-1)
  7. 第二种是第一次跳两级,此时的跳法数目等于后面剩下的n-2级台阶的跳法数目,即为f(n-2)
  8. 因此,n级台阶的不同跳法的总数为f(n)=f(n-1)+f(n-2)。
  1. public class Solution {
  2. public int JumpFloor(int target) {
  3. if (target <= 0) {
  4. return 0;
  5. }
  6. if (target >0 && target <= 2) {
  7. return target;
  8. }
  9. int pre = 1;
  10. int p = 2;
  11. int res = 0;
  12. for (int i = 3; i <= target; i++) {
  13. res = pre + p;
  14. pre = p;
  15. p = res;
  16. }
  17. return res;
  18.  
  19. }
  20. }

变态跳台阶

  1. 题目描述
  2. 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
  1. 这个可以用数学来解释
  2. F(n) = Fn-1)+F(n-2)+...+F(1)
  3. F(n-1) = Fn-2)+F(n-3)+...+F(1)
  4. 两个式子相减,很容易得出F(n)=2F(n-1)
  5. 每个台阶都有跳与不跳两种情况(除了最后一个台阶),最后一个台阶必须跳。所以共用2^(n-1)中情况
  1. public class Solution {
  2. public int JumpFloorII(int target) {
  3. if (target == 0) {
  4. return 0;
  5. }
  6. if (target == 1) {
  7. return 1;
  8. }
  9. return 2 * JumpFloorII(target - 1);
  10. }
  11. }

--------------------------------------------------

矩形覆盖

  1. 题目描述
  2. 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
  1. 解题思路:
  2. 假设2*n的矩形的覆盖方法为f(8)
  3. 用第一个2x1的小矩形区覆盖大矩形的最左边有两种选择,竖着放或者横着放。当竖着放的时候,右边还剩2*(n-1)的区域,覆盖的方法有f(n-1)种。当横着放的税后,左下角也得横着放一个小矩形,右边还剩2*(n-2),覆盖的方法还有f(n-2).即f(n)=f(n-1)+f(n-2)
  1. public class Solution {
  2. public int RectCover(int target) {
  3. if (target <= 0) {
  4. return 0;
  5. }
  6. if (target > 0 && target <= 2) {
  7. return target;
  8. }
  9. int pre = 1;
  10. int p = 2;
  11. int res = 0;
  12. for (int i = 3; i <= target; i++) {
  13. res = p + pre;
  14. pre = p;
  15. p = res;
  16. }
  17. return res;
  18.  
  19. }
  20. }

---------------------------------------------------------------------------------

旋转数组的最小数字

  1. 题目描述
  2. 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。
    例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0

这个题目分为有重复元素和没有重复元素两种情况,没有重复元素时,利用二分法,这个时候首先要判断nums[mid]>nums[high],如果是的话,最小值肯定在在mid和high之间,令low=mid+1;否则的话领high=mid,代码如下:

  1. public class Solution {
  2. public int findMin(int[] nums) {
  3. if (nums.length == 0 || nums == null) {
  4. return -1;
  5. }
  6. int low = 0;
  7. int high = nums.length - 1;
  8. if (nums[low] < nums[high]) {
  9. return nums[low];
  10. }
  11. int mid;
  12. while (low < high) {
  13. mid = low + ((high - low) >> 1);
  14. if (nums[mid] > nums[high]) {
  15. low = mid + 1;
  16. } else {
  17. high = mid;
  18. }
  19. }
  20. return nums[low];
  21. }
  22. }

那么判断nums[mid]>nums[high],如果是的话,那么最小值肯定在mid和high中间,然后判断nums[mid]<nums[low],如果是的话最小值肯定在low和mid中间;否则的话都有可能,这个时候只需要令high--,代码如下:

  1. public class Solution {
  2. public int findMin(int[] nums) {
  3. int low = 0;
  4. int high = nums.length - 1;
  5. if (nums[low] < nums[high]) {
  6. return nums[low];
  7. }
  8. int mid;
  9. while (low < high) {
  10. mid = low + ((high - low) >> 1);
  11. if (nums[mid] > nums[high]) {
  12. low = mid + 1;
  13. } else if (nums[mid] < nums[high]) {
  14. high = mid;
  15. } else {
  16. high--;
  17. }
  18. }
  19. return nums[low];
  20. }
  21. }

------------------------------------------------------------------------

搜索旋转排序数组

  1. 描述
  2. 假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1
  3.  
  4. 你可以假设数组中不存在重复的元素。
  5.  
  6. 您在真实的面试中是否遇到过这个题?
  7. 样例
  8. 给出[4, 5, 1, 2, 3]和target=1,返回 2
  9.  
  10. 给出[4, 5, 1, 2, 3]和target=0,返回 -1
  11.  
  12. 挑战
  13. O(logN) time
  1. 解题思路
  2. 这个题目解得时候,首先查找mid下标元素的值,判断nums[mid]是否等于target
    如果是,返回1;如果不是的话就与low位置的值相比较,判断nums[low]<nums[mid],
    如果是,那么这个范围内的数字是单调递增的,如果不是,那么这个范围内的数字不是单调的。
    如果是单调递增的,那么判断这个nums[low]<=target<=nums[mid],是的话那么让high=mid,否则的话low=mid+1,;
    如果不是单调递增的话,那么判断nums[mid]=<target<=nums[high],如果是的话,令low=mid,否则的话让high=mid-1
    由于区间是low+1<high,所以最后要对结果进行验证,判断lowhigh哪一个符合要求,具体代码如下:
  1. public class Solution {
  2. public int search(int[] nums, int target) {
  3. if (nums.length == 0 || nums == null) {
  4. return -1;
  5. }
  6. int low = 0;
  7. int high = nums.length - 1;
  8. while(low + 1 < high) {
  9. int mid = low + ((high - low) >> 1);
  10. if (nums[mid] == target) {
  11. return mid;
  12. }
  13. if (nums[mid] > nums[low]) {//前半部分是升序
  14. if (target >= nums[low] && target <= nums[mid]) {//待查找的元素再升序子序列中
  15. high = mid;
  16. } else {
  17. low = mid + 1;
  18. }
  19. } else if (nums[mid] < nums[low]){//前半部分不是升序
  20. if (target >= nums[mid] && target <= nums[high]) {
  21. low = mid;
  22. } else {
  23. high = mid - 1;
  24. }
  25. }
  26. }
  27. if (nums[low] == target) {
  28. return low;
  29. }
  30. if (nums[high] == target) {
  31. return high;
  32. }
  33. return -1;
  34. }
  35. }

另一种情况是旋转数组中存在重复元素的时候,这个时候与上面基本相似,就是加一个判断如果nums[mid]=nums[low]的话,就是让low++,具体代码如下:

  1. public class Solution {
  2. public boolean search(int[] nums, int target) {
  3. if (nums.length == 0 || nums == null) {
  4. return false;
  5. }
  6. int low = 0;
  7. int high = nums.length - 1;
  8. while(low + 1 < high) {
  9. int mid = low + ((high - low) >> 1);
  10. if (nums[mid] == target) {
  11. return true;
  12. }
  13. if (nums[mid] > nums[low]) {//前半部分是升序
  14. if (target >= nums[low] && target <= nums[mid]) {//待查找的元素再升序子序列中
  15. high = mid;
  16. } else {
  17. low = mid + 1;
  18. }
  19. } else if (nums[mid] < nums[low]){//前半部分不是升序
  20. if (target >= nums[mid] && target <= nums[high]) {
  21. low = mid;
  22. } else {
  23. high = mid - 1;
  24. }
  25. } else {
  26. low++;
  27. }
  28. }
  29. if (nums[low] == target) {
  30. return true;
  31. }
  32. if (nums[high] == target) {
  33. return true;
  34. }
  35. return false;
  36. }
  37. }

--------------------------------------------------------------------------------------------------------------

二进制中1的个数

  1. 题目描述
  2. 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
  1. 解题思路:
    n&(n-1)
  2. 该位运算去除 n 的位级表示中最低的1那一位。
  3.  
  4. n : 10110100
  5. n-1 : 10110011
  6. n&(n-1) : 10110000
  7. 时间复杂度:O(M),其中 M 表示 1 的个数。
  1. public class Solution {
  2. public int NumberOf1(int n) {
  3. int count = 0;
  4. while (n != 0) {
  5. count++;
  6. n &= n - 1;
  7. }
  8. return count++;
  9.  
  10. }
  11. }
  1. 相关题目:
  2. 1.判断一个整数是不是2的整数次方。如果一个整数是2的整数次方,那么它的二进制表示中只有一位是1
    所以把这个整数减去1之后再和它自己做与运算,这个整数中唯一的1就会变成0.
  3.  
  4. 2.输入两个整数m,n,计算需要改变m的二进制表示中的多少位才能得到n。比如10的二进制为1010,13的二进制为1101
    需要改变10103为才能得到1101.分为两步解决,第一步求这连个数的异或;第二步统计异或结果中1的位数。

-----------------------------------------------------------------------------------------

数值的整数次方

  1. 题目描述
  2. 给定一个double类型的浮点数baseint类型的整数exponent。求baseexponent次方。
  1. 思路分析:
  2. 就是求解一个数的幂级数并返回,这道题的一个思路就是利用二分法,判断n的值,
    如果n=0,直接返回1,如果n=1,返回x,否则的话判断n的奇偶性,
    如果n是偶数,那么xn次方就可以分解成两个xn/2次方相乘,然后继续分解;
    如果是奇数,那么直接分解成两个xn/2次方相乘再乘以x,然后递归的调用分解函数就行,具体代码如下;
  1. public class Solution {
  2. public double Power(double base, int exponent) {
  3. if (exponent == 0) {
  4. return 1;
  5. }
  6. if (exponent == 1) {
  7. return base;
  8. }
  9. if (exponent > 0) {
  10. return pow(base, exponent);
  11. } else {
  12. return 1 / pow(base, -exponent);
  13. }
  14. }
  15. public double pow(double x, int n) {
  16. if (n == 1) {
  17. return x;
  18. }
  19. double half = pow(x, n >>> 1);
  20. if (n % 2 == 0) {
  21. return half * half;
  22. } else {
  23. return half * half * x;
  24. }
  25. }
  26. }

------------------------------------------------------------------------

调整数组顺序使奇数位于偶数前面

  1. 题目描述
  2. 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
  1. public class Solution {
  2. public void reOrderArray(int [] array) {
  3. if (array == null || array.length == 0) {
  4. return;
  5. }
  6. int oddCnt = 0;
  7. for (int i = 0; i < array.length; i++) {
  8. if (array[i] % 2 == 1) {
  9. oddCnt++;
  10. }
  11. }
  12. int[] copy = array.clone();
  13. int i = 0, j = oddCnt;
  14. for (int num : copy) {
  15. if (num % 2 == 1) {
  16. array[i++] = num;
  17. } else {
  18. array[j++] = num;
  19. }
  20. }
  21. }
  22. }

----------------------------------------------------------------------------------

链表中倒数第k个结点

  1. 题目描述
  2. 输入一个链表,输出该链表中倒数第k个结点。
  1. 解题思路
  2. 声明两个指针,第一个先后移k,然后两个指针同时后移,直到第一个到达最后。
  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5.  
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. public class Solution {
  11. public ListNode FindKthToTail(ListNode head,int k) {
  12. if (head == null || k <= 0) {
  13. return null;
  14. }
  15. ListNode p = head;
  16. ListNode pre = head;
  17. while (p != null && k != 0) {
  18. p = p.next;
  19. k--;
  20. }
  21. if (k > 0) {
  22. return null;
  23. }
  24. while (p != null) {
  25. p = p.next;
  26. pre = pre.next;
  27. }
  28. return pre;
  29.  
  30. }
  31. }

---------------------------------------------------------------------------

反转链表

  1. 题目描述
  2. 输入一个链表,反转链表后,输出新链表的表头。
  1. 有递归和非递归两种实现方式,对于非递归方式,
    首先要定要三个指针,pre表示前驱节点,p表示当前节点,next表示下一个节点,
    非递归的时候有非常固定的模式,
    next=p.next,p.next=pre,pre=p,p=next;
  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5.  
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. public class Solution {
  11. public ListNode ReverseList(ListNode head) {
  12. if (head == null || head.next == null) {
  13. return head;
  14. }
  15. ListNode pre = head;
  16. ListNode p = head.next;
  17. ListNode next = null;
  18. while (p != null) {
  19. next = p.next;
  20. p.next = pre;
  21. pre = p;
  22. p = next;
  23. }
  24. head.next = null;
  25. return pre;
  26.  
  27. }
  28. }
  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5.  
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. public class Solution {
  11. public ListNode ReverseList(ListNode head) {
  12. if (head == null || head.next == null) {
  13. return head;
  14. }
  15. ListNode next = head.next;
  16. head.next = null;
  17. ListNode newHead = ReverseList(next);
  18. next.next = head;
  19. return newHead;
  20.  
  21. }
  22. }

-------------------------------------------------------------------------------------

合并两个排序的链表

  1. 题目描述
  2. 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
  1. 将两个有序链表合并成一个有序链表,首先判断一下是否有一个为空,如果是的话返回另外一个,然后从头结点开始判断哪一个链表的节点值小,
  2. 将小的一个节点插入到新建的链表中,同时指针向后移动一个,最后知道有一个链表为空结束。最后还要判断哪一个链表没有结束,直接将新链表的next指向没有结束的链表即可.
  3. 另外还有一种递归的算法,直接比较两个链表的头结点大小,将小的一个作为新的头结点,然后递归的调用函数.
  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5.  
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. public class Solution {
  11. public ListNode Merge(ListNode list1,ListNode list2) {
  12. if (list1 == null) {
  13. return list2;
  14. }
  15. if (list2 == null) {
  16. return list1;
  17. }
  18. ListNode dummy = new ListNode(0);
  19. ListNode p = dummy;
  20. while (list1 != null && list2 != null) {
  21. if (list1.val < list2.val) {
  22. p.next = list1;
  23. list1 = list1.next;
  24. } else {
  25. p.next = list2;
  26. list2 = list2.next;
  27. }
  28. p = p.next;
  29. }
  30. p.next = (list1 == null) ? list2 : list1;
  31. return dummy.next;
  32. }
  33. }
  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5.  
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. public class Solution {
  11. public ListNode Merge(ListNode list1,ListNode list2) {
  12. if (list1 == null) {
  13. return list2;
  14. }
  15. if (list2 == null) {
  16. return list1;
  17. }
  18. if (list1.val < list2.val) {
  19. list1.next = Merge(list1.next, list2);
  20. return list1;
  21. } else {
  22. list2.next = Merge(list1, list2.next);
  23. return list2;
  24. }
  25. }
  26. }

-------------------------------------------------------------------------------

删除链表中重复的结点

  1. 题目描述
  2. 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
  1. 把所有重复的元素都要删除,因为头结点可能也是重复元素,所以要声明新的头结点,同样这次要声明三个指针pre,p,next
  2.  
  3. pre初始化指向新生命的头结点,p初始化为头结点,要判断pnext的值是否相等,所以这两者都不能为空。直接判断p.val是否等于next.val,如果相等
  4.  
  5. next后移直至不相等,然后pre.next = nextp = next,这样就将重复的元素都删除了,如果不想等的话直接将pre = p;p = p.next;然后继续执行循环,
  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5.  
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. public ListNode deleteDuplication(ListNode pHead)
  13. {
  14. if (pHead == null || pHead.next == null) {
  15. return pHead;
  16. }
  17. ListNode dummy = new ListNode(0);
  18. dummy.next = pHead;
  19. ListNode pre = dummy;
  20. ListNode p = pHead;
  21. ListNode next = null;
  22. while (p != null && p.next != null) {
  23. next = p.next;
  24. if (p.val == next.val) {
  25. while (next != null && next.val == p.val) {
  26. next = next.next;
  27. }
  28. pre.next = next;
  29. p = next;
  30. } else {
  31. pre = p;
  32. p = p.next;
  33. }
  34. }
  35. return dummy.next;
  36.  
  37. }
  38. }

----------------------------------------------------------------

链表中环的入口结点

  1. 题目描述
  2. 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null

利用快慢指针做,判断时主要有以下依据:

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5.  
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12.  
  13. public ListNode EntryNodeOfLoop(ListNode pHead)
  14. {
  15. if (pHead == null) {
  16. return null;
  17. }
  18. ListNode fast = pHead;
  19. ListNode slow = pHead;
  20. while (fast != null && fast.next != null) {
  21. fast = fast.next.next;
  22. slow = slow.next;
  23. if (slow == fast) {
  24. slow = pHead;
  25. while (slow != fast) {
  26. slow = slow.next;
  27. fast = fast.next;
  28. }
  29. return fast;
  30. }
  31. }
  32. return null;
  33. }
  34. }

----------------------------------------------------------------------------------------

剑指offer题解的更多相关文章

  1. 剑指offer题解(Java版)

    剑指offer题解(Java版) 从尾到头打印链表 题目描述 输入一个链表,按从尾到头的顺序返回一个ArrayList. 方法1:用一个栈保存从头到尾访问链表的每个结点的值,然后按出栈顺序将各个值存入 ...

  2. 剑指Offer题解(Python版)

    https://blog.csdn.net/tinkle181129/article/details/79326023# 二叉树的镜像    链表中环的入口结点    删除链表中重复的结点    从尾 ...

  3. 剑指Offer题解索引

    数组 数组中重复的数字 二维数组中的查找 构建乘积数组 字符串 替换空格 字符流中第一个不重复的字符 表示数值的字符串 递归和循环 斐波那契数列 跳台阶 变态跳台阶 矩形覆盖 链表 从尾到头打印链表 ...

  4. 剑指offer题解02-10

    02 单例模式 单例模式,是一种常用的软件设计模式.在它的核心结构中只包含一个被称为单例的特殊类.通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例.即一个类只有一个对象实例. 从具体实现角 ...

  5. 【剑指offer】(第 2 版)Java 题解

    [剑指offer](第 2 版)Java 题解 第一章 面试的流程 略... 第二章 面试需要的基础知识 面试题 1. 赋值运算符函数 面试题 2. 实现 Singleton 模式 Solution ...

  6. 《剑指offer》题解

    有段时间准备找工作,囫囵吞枣地做了<剑指offer>提供的编程习题,下面是题解收集. 当初没写目录真是个坏习惯(-_-)||,自己写的东西都要到处找. 提交的源码可以在此repo中找到:h ...

  7. LeetCode题解汇总(包括剑指Offer和程序员面试金典,持续更新)

    LeetCode题解汇总(持续更新,并将逐步迁移到本博客列表中) LeetCode题解分类汇总(包括剑指Offer和程序员面试金典) 剑指Offer 序号 题目 难度 03 数组中重复的数字 简单 0 ...

  8. LeetCode题解分类汇总(包括剑指Offer和程序员面试金典,持续更新)

    LeetCode题解汇总(持续更新,并将逐步迁移到本博客列表中) 剑指Offer 数据结构 链表 序号 题目 难度 06 从尾到头打印链表 简单 18 删除链表的节点 简单 22 链表中倒数第k个节点 ...

  9. C++版 - 剑指offer 面试题23:从上往下打印二叉树(二叉树的层次遍历BFS) 题解

    剑指offer  面试题23:从上往下打印二叉树 参与人数:4853  时间限制:1秒  空间限制:32768K 提交网址: http://www.nowcoder.com/practice/7fe2 ...

随机推荐

  1. vb.net 使用NPOI控制Excel檔

    '導入命名空間 Imports NPOI.HSSF.UserModelImports NPOI.HPSFImports NPOI.POIFS.FileSystem Private Sub A1()'方 ...

  2. 【原】ActiveMq实现分布式事务一致性

    前言:关于分布式事务话题一直是颇有争议的话题,在本文中通过ActiveMq 实现分布式事务做一个简单的demo;同时也让自己能在实践中可以获取经验和对分布式事务自己的一些思考. 1.本地事务 我们通常 ...

  3. 8.并发容器ConcurrentHashMap#put方法解析

    jdk1.7.0_79 HashMap可以说是每个Java程序员用的最多的数据结构之一了,无处不见它的身影.关于HashMap,通常也能说出它不是线程安全的.这篇文章要提到的是在多线程并发环境下的Ha ...

  4. MVC中的HtmlHelper详解

    熟悉MVC开发的朋友都应该知道在MVC中,每一个Controller都对应一个View,并且CS文件和对应的ASPX文件也被分离了,更重要的是不再有服务器端控件在工具箱中,不再是代码后至了.MVC中的 ...

  5. jsp使用servlet实现文件上传

    1.在index.jsp中写入以下代码 <form method="post" action="demo3" enctype="multipar ...

  6. HDU5037(SummerTrainingDay01-C)

    Frog Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)Total Subm ...

  7. Python: tree data structure

    # 树结构 from pythonds.basic.stack import Stack #pip install pythonds from pythonds.trees.binaryTree im ...

  8. ES6中Object.is方法比较两个值是否相等

    Object.is: let obj={a:1,b:2}; Object.is(obj,obj);//true Object.is(obj,{obj});//false Object.is({},{} ...

  9. VUE CLI 3.0 安装及创建项目

    一.安装 VUE CLI 3.0 官网: https://cli.vuejs.org/   详细资料可以自己先把官网过一遍. 1. 安装(默认你的电脑上已安装node及npm) npm install ...

  10. 安卓开发中strings.xml的使用

    为了使用方便也是为了代码规范化,我们都将文字信息放在res-values-strings.xml中, 因为开发中需要用到将文字的换行,百度了一下,可以将文字段信息直接在strings.xml文件中换行 ...