From a943f5e1197d1f875e9a0322150e3d9587adf992 Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Thu, 7 Dec 2023 10:54:35 +0800 Subject: [PATCH] leetcode: Add search insert position --- Cargo.lock | 4 ++ .../0035.search-insert-position/Cargo.toml | 7 +++ .../0035.search-insert-position/src/main.rs | 45 +++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 leetcode/0035.search-insert-position/Cargo.toml create mode 100644 leetcode/0035.search-insert-position/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 97548b77..3961f0f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -346,6 +346,10 @@ version = "0.1.0" name = "lc-0027-remove-element" version = "0.1.0" +[[package]] +name = "lc-0035-search-insert-position" +version = "0.1.0" + [[package]] name = "lc-0053-maximum-subarray" version = "0.1.0" diff --git a/leetcode/0035.search-insert-position/Cargo.toml b/leetcode/0035.search-insert-position/Cargo.toml new file mode 100644 index 00000000..988f2592 --- /dev/null +++ b/leetcode/0035.search-insert-position/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-0035-search-insert-position" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/leetcode/0035.search-insert-position/src/main.rs b/leetcode/0035.search-insert-position/src/main.rs new file mode 100644 index 00000000..2c29e51e --- /dev/null +++ b/leetcode/0035.search-insert-position/src/main.rs @@ -0,0 +1,45 @@ +// Copyright (c) 2023 Xu Shaohua . 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, 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); +}