rust练习-1

2022-04-15  本文已影响0人  robertzhai

总结

vector 用法
hashmap 用户
类型转换
变量值互换
for + loop 循环遍历
mut 可变变量
match匹配

1.https://leetcode.cn/problems/two-sum/submissions/

use std::collections::HashMap;


impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut map = HashMap::new();
        let len = nums.len();
        let mut diff = 0;
        for index in 0..len {
            diff = target - nums[index];
            map.insert(diff, index);
        }
        let mut result: Vec<i32> = Vec::new();
        for index in 0..len {
            
             match map.get(&nums[index]) {
                Some(v) => {

                    let tmp:i32 = (*v) as i32;
                    if tmp != index as i32 {
                        result.push(index as i32);
                        result.push(tmp);
                        return result;
                    }
                    
                },
                None => {

                },
            } 
        }
        return result

    }
}

2.https://leetcode.cn/problems/climbing-stairs/

impl Solution {
    pub fn climb_stairs(n: i32) -> i32 {

    
        if n < 2 as i32 {
            return 1;
        }
        let mut f0 = 1;
        let mut f1 = 1;
        let mut temp = 0;
        let mut index = 1;
        loop {
            index += 1;
            temp = f0;
            f0 = f1;
            f1 = f1 + temp;
            if index == n {
                break;
            }
        }
        f1

    }
}

3.https://leetcode.cn/problems/palindrome-number/

impl Solution {
    pub fn is_palindrome(x: i32) -> bool {
        let mut num = x as i32;
        if num < 0 {
            return false
        }
        let mut rev_num:i32 = 0;
        loop {
            if num > 0 {
                rev_num = rev_num*10 + num%10;
                num = num /10;
            } else {
                break;
            }
            
        }
        return x == rev_num

    }
}
上一篇 下一篇

猜你喜欢

热点阅读