• 笔试刷题Day—8


    两数之和

    在这里插入图片描述

    方法1:暴力法
    思想:双重for循环直接遍历数组元素,找到target数值。找不到则返回false。

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> res(2);
            if (nums.empty())return res;
            int length = nums.size();
            for(int i = 0;i<length;i++){
                for(int j = i+1;j<length;j++){
                    if(nums[i]+nums[j] == target){
                        res[0] = i;
                        res[1] = j;
                    }
                }
            }
            return res;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    耗时时间很长,不推荐使用该方法。
    在这里插入图片描述
    方法2:哈希表
    创建一个哈希表,然后循环一次,寻找target。

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int,int> hash;
            vector<int> ans;
            for(int i = 0;i<nums.size();i++){
                int num = nums[i];
                auto pos = hash.find(target - num);
                if(pos == hash.end()){
                    hash[num] = i;
    
                }else {
                    ans.push_back(pos->second);//ans入栈操作
                    ans.push_back(i);//ans入栈操作
                    break;
                }
            }
            return ans;
        }       
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    效率高,时间短,推荐使用。
    在这里插入图片描述

    实现strStr

    在这里插入图片描述暴力强解法:

    
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int n = haystack.size(), m = needle.size();
            for (int i = 0; i + m <= n; i++) {
                bool flag = true;
                for (int j = 0; j < m; j++) {
                    if (haystack[i + j] != needle[j]) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    return i;
                }
            }
            return -1;
        }
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    用Python实现链式调用
    C++零碎记录(八)
    egg(二十):fs读取本地的txt文件
    【数据结构-栈 二】【单调栈】每日温度、接雨水
    部署LVS-NAT群集实验
    第16章_瑞萨MCU零基础入门系列教程之CAN 协议
    AOP面向切面编程
    Nacos整合Gateway入门示例
    Mybatis 动态SQL – 使用trim标签替代where,set标签
    作用域和作用域链
  • 原文地址:https://blog.csdn.net/m0_46152793/article/details/126593008