704:二分查找

This commit is contained in:
huangge1199 2021-07-06 16:41:28 +08:00
parent 8143515901
commit 023c2b1c17
3 changed files with 80 additions and 1 deletions

View File

@ -0,0 +1,52 @@
//给定一个 n 个元素有序的升序整型数组 nums 和一个目标值 target 写一个函数搜索 nums 中的 target如果目标值存在返回下标
//则返回 -1
//
//
//示例 1:
//
// 输入: nums = [-1,0,3,5,9,12], target = 9
//输出: 4
//解释: 9 出现在 nums 中并且下标为 4
//
//
// 示例 2:
//
// 输入: nums = [-1,0,3,5,9,12], target = 2
//输出: -1
//解释: 2 不存在 nums 中因此返回 -1
//
//
//
//
// 提示
//
//
// 你可以假设 nums 中的所有元素是不重复的
// n 将在 [1, 10000]之间
// nums 的每个元素都将在 [-9999, 9999]之间
//
// Related Topics 数组 二分查找
// 👍 256 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
//704:二分查找
public class BinarySearch {
public static void main(String[] args) {
//测试代码
Solution solution = new BinarySearch().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int search(int[] nums, int target) {
int result = Arrays.binarySearch(nums, target);
return result < 0 ? -1 : result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,27 @@
<p>给定一个&nbsp;<code>n</code>&nbsp;个元素有序的(升序)整型数组&nbsp;<code>nums</code> 和一个目标值&nbsp;<code>target</code> &nbsp;,写一个函数搜索&nbsp;<code>nums</code>&nbsp;中的 <code>target</code>,如果目标值存在返回下标,否则返回 <code>-1</code></p>
<p><br>
<strong>示例 1:</strong></p>
<pre><strong>输入:</strong> <code>nums</code> = [-1,0,3,5,9,12], <code>target</code> = 9
<strong>输出:</strong> 4
<strong>解释:</strong> 9 出现在 <code>nums</code> 中并且下标为 4
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre><strong>输入:</strong> <code>nums</code> = [-1,0,3,5,9,12], <code>target</code> = 2
<strong>输出:</strong> -1
<strong>解释:</strong> 2 不存在 <code>nums</code> 中因此返回 -1
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li>你可以假设 <code>nums</code>&nbsp;中的所有元素是不重复的。</li>
<li><code>n</code>&nbsp;将在&nbsp;<code>[1, 10000]</code>之间。</li>
<li><code>nums</code>&nbsp;的每个元素都将在&nbsp;<code>[-9999, 9999]</code>之间。</li>
</ol>
<div><div>Related Topics</div><div><li>数组</li><li>二分查找</li></div></div>\n<div><li>👍 256</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long