[关闭]
@Yano 2015-12-30T03:24:58.000000Z 字数 7282 阅读 6950

LeetCode之Binary Search题目汇总

LeetCode

我的博客:http://blog.csdn.net/yano_nankai
LeetCode题解:https://github.com/LjyYano/LeetCode


LeetCode 题目汇总

LeetCode之Array题目汇总
LeetCode之Hash Table题目汇总
LeetCode之Linked List题目汇总
LeetCode之Math题目汇总
LeetCode之String题目汇总
LeetCode之Binary Search题目汇总
LeetCode之Divide and Conquer题目汇总
LeetCode之Dynamic Programming题目汇总
LeetCode之Backtracing题目汇总
LeetCode之Stack题目汇总
LeetCode之Sort题目汇总
LeetCode之Bit Manipulation题目汇总
LeetCode之Tree题目汇总
LeetCode之Depth-first Search题目汇总
LeetCode之Breadth-first Search题目汇总
LeetCode之Graph题目汇总
LeetCode之Trie题目汇总
LeetCode之Design题目汇总


文章目录:


Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.


  1. public int countNodes(TreeNode root) {
  2. if (root == null) {
  3. return 0;
  4. }
  5. int leftHeight = 0;
  6. int rightHeight = 0;
  7. // 计算leftHeight
  8. TreeNode p = root;
  9. while (p != null) {
  10. p = p.left;
  11. leftHeight++;
  12. }
  13. // 计算rightHeight
  14. p = root;
  15. while (p != null) {
  16. p = p.right;
  17. rightHeight++;
  18. }
  19. // 如果相等,满足2^n-1
  20. if (leftHeight == rightHeight) {
  21. return (1 << leftHeight) - 1;
  22. }
  23. return 1 + countNodes(root.left) + countNodes(root.right);
  24. }

Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.


  1. public int divide(int dividend, int divisor) {
  2. if (divisor == 0) {
  3. return Integer.MAX_VALUE;
  4. }
  5. int result = 0;
  6. if (dividend == Integer.MIN_VALUE) {
  7. result = 1;
  8. if (divisor == -1) {
  9. return Integer.MAX_VALUE;
  10. }
  11. dividend += Math.abs(divisor);
  12. }
  13. if (divisor == Integer.MIN_VALUE) {
  14. return result;
  15. }
  16. boolean isNeg = ((dividend ^ divisor) >>> 31 == 1) ? true : false;
  17. dividend = Math.abs(dividend);
  18. divisor = Math.abs(divisor);
  19. int c = 0;
  20. while (divisor <= (dividend >> 1)) {
  21. divisor <<= 1;
  22. c++;
  23. }
  24. while (c >= 0) {
  25. if (dividend >= divisor) {
  26. dividend -= divisor;
  27. result += 1 << c;
  28. }
  29. divisor >>= 1;
  30. c--;
  31. }
  32. System.out.println(result);
  33. return isNeg ? -result : result;
  34. }

Find Minimum in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.


数列基本有序,使用二分查找。分为3种情况:

假设数列是n,s是起始下标,e是最后下标,m是中间元素下标。

n[s] < n[e]

0 1 2 4 5 6 7

这种情况,直接返回n[s]。因为数列是有序的,或者只是旋转过一次。如果n[s] < n[e],则表明没有旋转。最小元素是n[s]。

n[m] > n[s] > n[e]

4 5 6 7 0 1 2

只需要满足n[m] > n[s]即可,因为第一种情况排除后,n[s]就一定会 > n[e]。

在本例中:

  1. n[s] = 4
  2. n[m] = 7
  3. n[e] = 2

则最小值肯定在7之后,到2之间,即 [m+1, e]。

n[m] < n[e] < n[s]

6 7 0 1 2 4 5

n[m] < n[e],在本例中:

  1. n[s] = 6
  2. n[m] = 1
  3. n[e] = 5

则表明,从m到e,数组已经是上升的,所以最小值在[s, m]。

  1. public int findMin(int[] nums) {
  2. if (nums.length == 1) {
  3. return nums[0];
  4. }
  5. if (nums.length == 2) {
  6. return Math.min(nums[0], nums[1]);
  7. }
  8. int s = 0, e = nums.length - 1;
  9. int m = (s + e) / 2;
  10. if (nums[s] < nums[e]) {
  11. return nums[s];
  12. }
  13. if (nums[m] > nums[s]) {
  14. return findMin(Arrays.copyOfRange(nums, m + 1, e + 1));
  15. }
  16. return findMin(Arrays.copyOfRange(nums, s, m + 1));
  17. }

Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


  1. public int findPeakElement(int[] nums) {
  2. int low = 0;
  3. int high = nums.length - 1;
  4. while (low < high) {
  5. int mid = low + (high - low) / 2;
  6. if (nums[mid] > nums[mid + 1]) {
  7. high = mid;
  8. } else {
  9. low = mid + 1;
  10. }
  11. }
  12. return low;
  13. }

First Bad Version

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


  1. public int firstBadVersion(int n) {
  2. int low = 1, high = n;
  3. while (low < high) {
  4. int mid = low + (high - low) / 2;
  5. if (isBadVersion(mid)) {
  6. high = mid;
  7. } else {
  8. low = mid + 1;
  9. }
  10. }
  11. return low;
  12. }

H-Index II

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

Hint:

  1. Expected runtime complexity is in O(log n) and the input is sorted.

  1. public int hIndex(int[] citations) {
  2. int n = citations.length;
  3. int low = 0, high = n - 1;
  4. while (low <= high) {
  5. int mid = low + (high - low) / 2;
  6. if (citations[mid] == n - mid) {
  7. return n - mid;
  8. } else if (citations[mid] < n - mid) {
  9. low = mid + 1;
  10. } else {
  11. high = mid - 1;
  12. }
  13. }
  14. return n - low;
  15. }

Pow(x, n)

Implement pow(xn).


  1. public double myPow(double x, int n) {
  2. if (n < 0) {
  3. return 1 / pow(x, -n);
  4. } else {
  5. return pow(x, n);
  6. }
  7. }
  8. private double pow(double x, int n) {
  9. if (n == 0) {
  10. return 1;
  11. }
  12. double v = pow(x, n / 2);
  13. if (n % 2 == 0) {
  14. return v * v;
  15. } else {
  16. return v * v * x;
  17. }
  18. }

Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].


  1. public int[] searchRange(int[] nums, int target) {
  2. int l = 0, r = nums.length;
  3. while (l < r) {
  4. int m = l + (r - l) / 2;
  5. if (nums[m] == target) {
  6. int s = m, e = m;
  7. while (s - 1 >= 0 && nums[s - 1] == target) {
  8. s--;
  9. }
  10. while (e + 1 < nums.length && nums[e + 1] == target) {
  11. e++;
  12. }
  13. return new int[] { s, e };
  14. } else if (nums[m] > target) {
  15. r = m;
  16. } else {
  17. l = m + 1;
  18. }
  19. }
  20. return new int[] { -1, -1 };
  21. }

Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.


  1. public int search(int[] nums, int target) {
  2. int l = 0, r = nums.length - 1;
  3. while (l <= r) {
  4. int m = (l + r) / 2;
  5. if (nums[m] == target)
  6. return m;
  7. if (nums[l] < nums[m]) {
  8. if (target <= nums[m] && target >= nums[l])
  9. r = m - 1;
  10. else
  11. l = m + 1;
  12. } else if (nums[l] > nums[m]) {
  13. if (target >= nums[l] || target <= nums[m])
  14. r = m - 1;
  15. else
  16. l = m + 1;
  17. } else
  18. l++;
  19. }
  20. return -1;
  21. }

Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.


  1. public boolean search(int[] nums, int target) {
  2. int l = 0, r = nums.length - 1;
  3. while (l <= r) {
  4. int m = (l + r) / 2;
  5. if (nums[m] == target)
  6. return true;
  7. if (nums[l] < nums[m]) {
  8. if (target <= nums[m] && target >= nums[l])
  9. r = m - 1;
  10. else
  11. l = m + 1;
  12. } else if (nums[l] > nums[m]) {
  13. if (target >= nums[l] || target <= nums[m])
  14. r = m - 1;
  15. else
  16. l = m + 1;
  17. } else
  18. l++;
  19. }
  20. return false;
  21. }

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0


  1. public int searchInsert(int[] nums, int target) {
  2. if (nums == null || nums.length == 0) {
  3. return 0;
  4. }
  5. for (int i = 0; i < nums.length; i++) {
  6. if (target <= nums[i]) {
  7. return i;
  8. }
  9. }
  10. return nums.length;
  11. }

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.


  1. public int mySqrt(int x) {
  2. // 首先对负数和0进行处理
  3. if (x < 0) {
  4. return -1;
  5. } else if (x == 0) {
  6. return 0;
  7. }
  8. int start = 1;
  9. int end = x;
  10. while (start < end) {
  11. // 不能直接相加除以2,因为两个数相加可能溢出
  12. int m = start + (end - start) / 2;
  13. // 不能用m^2,(m+1)^2,因为可能溢出
  14. int m1 = x / m;
  15. int m2 = x / (m + 1);
  16. // m*2 == x
  17. if (m == m1) {
  18. return m;
  19. }
  20. // (m+1)^2 == x
  21. if (m + 1 == m2) {
  22. return m + 1;
  23. }
  24. // m*2 <= x && (m+1)^2 > x
  25. if (m < m1 && m + 1 > m2) {
  26. return m;
  27. }
  28. // m*2 > x
  29. if (m1 < m) {
  30. end = m;
  31. } else {
  32. // (m+1)^2 < x
  33. start = m + 1;
  34. }
  35. }
  36. return 1;
  37. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注