• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

LeetCode – Easy – 704. Binary Search

互联网 diligentman 1周前 (04-08) 8次浏览

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:

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

Example 2:

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

Constraints:

  • $1 <= nums.length <= 10^4$
  • $-9999 <= nums[i], target <= 9999$
  • All the integers in nums are unique.
  • nums is sorted in an ascending order.

Analysis

LeetCode - Easy - 704. Binary Search

Submission

public class BinarySearch {
	public int search(int[] nums, int target) {
		int left = 0, right = nums.length - 1, mid;

		while (left <= right) {
			mid = left + (right - left) / 2;

			if (nums[mid] < target) {
				left = mid + 1;
			} else if (nums[mid] > target) {
				right = mid - 1;
			} else {
				return mid;
			}
		}
		return -1;
	}
}

Test

import static org.junit.Assert.*;
import org.junit.Test;

public class BinarySearchTest {

	@Test
	public void test() {
		BinarySearch obj = new BinarySearch();

		assertEquals(4, obj.search(new int[] { -1, 0, 3, 5, 9, 12 }, 9));
		assertEquals(-1, obj.search(new int[] { -1, 0, 3, 5, 9, 12 }, 2));
		assertEquals(0, obj.search(new int[] {5}, 5));
	}
}

展开阅读全文

junitjava

© 著作权归作者所有

举报

打赏

0


0 收藏

微信
QQ
微博

分享

作者的其它热门文章

【清华大学】《逻辑学概论》笔记
《Java8实战》笔记(10):用Optional取代null
Kafka学习笔记
Redis学习笔记


程序员灯塔
转载请注明原文链接:LeetCode – Easy – 704. Binary Search
喜欢 (0)