Skip to content

Commit 3edd36e

Browse files
committedSep 14, 2024
Added rust
1 parent eade80a commit 3edd36e

File tree

101 files changed

+8146
-410
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

101 files changed

+8146
-410
lines changed
 

‎README.md

Lines changed: 410 additions & 410 deletions
Large diffs are not rendered by default.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 1\. Two Sum
5+
6+
Easy
7+
8+
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
9+
10+
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
11+
12+
You can return the answer in any order.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [2,7,11,15], target = 9
17+
18+
**Output:** [0,1]
19+
20+
**Output:** Because nums[0] + nums[1] == 9, we return [0, 1].
21+
22+
**Example 2:**
23+
24+
**Input:** nums = [3,2,4], target = 6
25+
26+
**Output:** [1,2]
27+
28+
**Example 3:**
29+
30+
**Input:** nums = [3,3], target = 6
31+
32+
**Output:** [0,1]
33+
34+
**Constraints:**
35+
36+
* <code>2 <= nums.length <= 10<sup>4</sup></code>
37+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
38+
* <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code>
39+
* **Only one valid answer exists.**
40+
41+
**Follow-up:** Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>) </code>time complexity?
42+
43+
## Solution
44+
45+
```rust
46+
use std::collections::HashMap;
47+
48+
impl Solution {
49+
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
50+
let mut index_map: HashMap<i32, usize> = HashMap::new();
51+
52+
for (i, &num) in numbers.iter().enumerate() {
53+
let required_num = target - num;
54+
if let Some(&index) = index_map.get(&required_num) {
55+
return vec![index as i32, i as i32];
56+
}
57+
index_map.insert(num, i);
58+
}
59+
60+
vec![-1, -1]
61+
}
62+
}
63+
```

0 commit comments

Comments
 (0)
Please sign in to comment.