File tree Expand file tree Collapse file tree 5 files changed +134
-0
lines changed
Expand file tree Collapse file tree 5 files changed +134
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=137 lang=rust
3+ *
4+ * [137] Single Number II
5+ */
6+
7+ // @lc code=start
8+ use std:: collections:: HashMap ;
9+
10+ impl Solution {
11+ pub fn single_number ( nums : Vec < i32 > ) -> i32 {
12+ Self :: bit_manipulation_sol ( nums)
13+ }
14+
15+ pub fn hashmap_sol ( nums : Vec < i32 > ) -> i32 {
16+ let mut map = HashMap :: new ( ) ;
17+
18+ for num in nums {
19+ if let Some ( v) = map. get_mut ( & num) {
20+ * v += 1 ;
21+ } else {
22+ map. insert ( num, 1 ) ;
23+ }
24+ }
25+
26+ for k in & map {
27+ if * k. 1 == 1 {
28+ return * k. 0 ;
29+ }
30+ }
31+
32+ 0
33+ }
34+
35+ pub fn bit_manipulation_sol ( nums : Vec < i32 > ) -> i32 {
36+ let mut x1 = 0 ;
37+ let mut x2 = 0 ;
38+ let mut mask = 0 ;
39+
40+ for num in nums {
41+ x2 ^= x1 & num;
42+ x1 ^= num;
43+ mask = !( x1 & x2) ;
44+ x2 &= mask;
45+ x1 &= mask;
46+ }
47+
48+ x1
49+ }
50+ }
51+ // @lc code=end
52+
Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=169 lang=rust
3+ *
4+ * [169] Majority Element
5+ */
6+
7+ // @lc code=start
8+ impl Solution {
9+ pub fn majority_element ( nums : Vec < i32 > ) -> i32 {
10+ let mut cnt = 1 ;
11+ let mut val = nums[ 0 ] ;
12+
13+ for i in 1 ..nums. len ( ) {
14+ if val != nums[ i] {
15+ if cnt == 0 {
16+ val = nums[ i] ;
17+ } else {
18+ cnt -= 1 ;
19+ }
20+ } else {
21+ cnt += 1 ;
22+ }
23+
24+
25+ }
26+
27+ val
28+ }
29+ }
30+ // @lc code=end
31+
Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=231 lang=rust
3+ *
4+ * [231] Power of Two
5+ */
6+
7+ // @lc code=start
8+ impl Solution {
9+ pub fn is_power_of_two ( mut n : i32 ) -> bool {
10+ if n == 0 {
11+ return false ;
12+ }
13+
14+ while n & 1 == 0 {
15+ n >>= 1 ;
16+ }
17+
18+ n == 1
19+ }
20+ }
21+ // @lc code=end
22+
Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=5 lang=rust
3+ *
4+ * [5] Longest Palindromic Substring
5+ */
6+
7+ // @lc code=start
8+ impl Solution {
9+ pub fn longest_palindrome ( s : String ) -> String {
10+ let N = s. len ( ) ;
11+ let chars: Vec < char > = s. chars ( ) . collect ( ) ;
12+
13+ let mut dp = vec ! [ vec![ false ; N ] ; N ] ;
14+ let mut ans = "" ;
15+ for j in 0 ..N {
16+ for i in ( 0 ..j+1 ) . rev ( ) {
17+ if chars[ i] == chars[ j] && ( j == 0 || i+1 >= j-1 || dp[ i+1 ] [ j-1 ] ) {
18+ dp[ i] [ j] = true ;
19+ if j - i + 1 > ans. len ( ) {
20+ ans = & s[ i..j+1 ] ;
21+ }
22+ }
23+ }
24+ }
25+ ans. to_string ( )
26+ }
27+ }
28+ // @lc code=end
29+
You can’t perform that action at this time.
0 commit comments