1.1-数组-704. 二分查找★

704. 二分查找

力扣题目链接,给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,搜索 nums 中的 target,如果存在返回下标,否则返回 -1n 将在 [1, 10000]之间。

  1. 可以假设 nums 中的所有元素是不重复的。
  2. n 将在 [1, 10000]之间。
  3. nums 的每个元素都将在 [-9999, 9999]之间。

示例 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

本地练习

rust 复制代码
pub struct Solution;

use std::cmp::Ordering;

impl Solution {
    pub fn search(nums: Vec<i32>, target: i32) -> i32 {
        
    }
}

fn main() {
    let res = [(vec![-1, 0, 3, 5, 9, 12], 9), (vec![-1, 0, 3, 5, 9, 12], 2)]
        .iter().map(|x| Solution::search(x.0.to_vec(), x.1)).collect::<Vec<_>>();
    println!("{:?}: {:?}", vec![4, -1] == res, res);
}

Rust答案

  • (版本一)左闭右开区间
rust 复制代码
use std::cmp::Ordering;
impl Solution {
    pub fn search(nums: Vec<i32>, target: i32) -> i32 {
        let (mut left, mut right) = (0, nums.len());
        while left < right {
            let mid = (left + right) / 2;
            match nums[mid].cmp(&target) {
                Ordering::Less => left = mid + 1,
                Ordering::Greater => right = mid,
                Ordering::Equal => return mid as i32,
            }
        }
        -1
    }
}
  • (版本二)左闭右闭区间
rust 复制代码
use std::cmp::Ordering;
impl Solution {
    pub fn search(nums: Vec<i32>, target: i32) -> i32 {
        let (mut left, mut right) = (0, nums.len());
        while left <= right {
            let mid = (right + left) / 2;
            match nums[mid].cmp(&target) {
                Ordering::Less => left = mid + 1,
                Ordering::Greater => right = mid - 1,
                Ordering::Equal => return mid as i32,
            }
        }
        -1
    }
}
相关推荐
栈与堆15 小时前
LeetCode 21 - 合并两个有序链表
java·数据结构·python·算法·leetcode·链表·rust
盛者无名1 天前
Rust的所有权(Owenership)
开发语言·rust
BlockChain8881 天前
MPC 钱包实战(三):Rust MPC Node + Java 调度层 + ETH 实际转账(可运行)
java·开发语言·rust
分布式存储与RustFS2 天前
RustFS在AI场景下的实测:从GPU到存储的完整加速方案
开发语言·人工智能·rust·对象存储·企业存储·rustfs·minio国产化替代
柠檬丶抒情2 天前
Rust no_std 裸机移植:9 条避坑与实战手册
开发语言·mongodb·rust
FAFU_kyp2 天前
Rust 流程控制学习教程
学习·算法·rust
FAFU_kyp2 天前
Rust 模式匹配:match 与 if let 详解
开发语言·后端·rust
Mr -老鬼3 天前
Java VS Rust
java·开发语言·rust
张心独酌3 天前
Rust开发案例库-静态服务器
服务器·开发语言·rust
liuxuzxx3 天前
使用Rust构建MCP Server Stdio类型
rust·mcp