Skip to content

Commit

Permalink
leetcode: Add search insert position
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Dec 7, 2023
1 parent 5f7bc37 commit a943f5e
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions leetcode/0035.search-insert-position/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-0035-search-insert-position"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
45 changes: 45 additions & 0 deletions leetcode/0035.search-insert-position/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright (c) 2023 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be
// found in the LICENSE file.

use std::cmp::Ordering;

// Binary search
pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
assert!(!nums.is_empty());

let mut low = 0;
let mut high = nums.len() - 1;
while low + 1 < high {
let middle = low + (high - low) / 2;
match nums[middle].cmp(&target) {
Ordering::Less => low = middle,
Ordering::Equal => return middle as i32,
Ordering::Greater => high = middle,
}
}
if nums[high] < target {
high as i32 + 1
} else if nums[low] > target {
low as i32 - 1
} else {
high as i32
}
}

fn main() {
let nums = vec![1, 3, 5, 6];
let target = 5;
let pos = search_insert(nums, target);
assert_eq!(pos, 2);

let nums = vec![1, 3, 5, 6];
let target = 2;
let pos = search_insert(nums, target);
assert_eq!(pos, 1);

let nums = vec![1, 3, 5, 6];
let target = 7;
let pos = search_insert(nums, target);
assert_eq!(pos, 4);
}

0 comments on commit a943f5e

Please sign in to comment.