LeetCode - Easy - 704. Binary Search

谁践踏了优雅 2022-11-17 03:51 209阅读 0赞

Topic

  • Binary Search

Description

https://leetcode.com/problems/binary-search/

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

Example 1:

  1. Input: nums = [-1,0,3,5,9,12], target = 9
  2. Output: 4
  3. Explanation: 9 exists in nums and its index is 4

Example 2:

  1. Input: nums = [-1,0,3,5,9,12], target = 2
  2. Output: -1
  3. Explanation: 2 does not exist in nums so return -1

Constraints:

  • 1 < = n u m s . l e n g t h < = 1 0 4 1 <= nums.length <= 10^4 1<=nums.length<=104
  • − 9999 < = n u m s [ i ] , t a r g e t < = 9999 -9999 <= nums[i], target <= 9999 −9999<=nums[i],target<=9999
  • All the integers in nums are unique.
  • nums is sorted in an ascending order.

Analysis

bd9cfb80cb63d8290c35d3717660dfaa.gif

Submission

  1. public class BinarySearch {
  2. public int search(int[] nums, int target) {
  3. int left = 0, right = nums.length - 1, mid;
  4. while (left <= right) {
  5. mid = left + (right - left) / 2;
  6. if (nums[mid] < target) {
  7. left = mid + 1;
  8. } else if (nums[mid] > target) {
  9. right = mid - 1;
  10. } else {
  11. return mid;
  12. }
  13. }
  14. return -1;
  15. }
  16. }

Test

  1. import static org.junit.Assert.*;
  2. import org.junit.Test;
  3. public class BinarySearchTest {
  4. @Test
  5. public void test() {
  6. BinarySearch obj = new BinarySearch();
  7. assertEquals(4, obj.search(new int[] { -1, 0, 3, 5, 9, 12 }, 9));
  8. assertEquals(-1, obj.search(new int[] { -1, 0, 3, 5, 9, 12 }, 2));
  9. assertEquals(0, obj.search(new int[] { 5}, 5));
  10. }
  11. }

发表评论

表情:
评论列表 (有 0 条评论,209人围观)

还没有评论,来说两句吧...

相关阅读