面试经典150题

打家劫舍

class Solution {
public:int rob(vector<int>& nums) {int n = nums.size();if(n == 1){return nums[0];}vector<int> dp(n, 0);dp[0] = nums[0];//有一间房可以偷//有两间房可以偷if(nums[1] > nums[0]){dp[1] = nums[1];}else{dp[1] = nums[0];}for (int i = 2; i < n; i++) {dp[i] = max(dp[i-1], dp[i-2]+nums[i]);}return dp[n-1];}
};

买股票的最佳时机

一次遍历

在这里插入图片描述

class Solution {
public:int maxProfit(vector<int>& prices) {int minPrice = INT_MAX, sum = 0;for(int price:prices){sum = max(sum, price-minPrice);minPrice = min(minPrice,price);}return sum;}
};

买股票的最佳时机二

给一个整数数组prices,其中prices[i]表示第i天价格。
动态规划
dp[i][0]:表示第i天交易完后手里没有股票的最大利润,dp[i][1]表示第i天交易完后手里持有一只的最大利润。

class Solution {
public:int maxProfit(vector<int>& prices) {int n = prices.size();if(n == 1){return 0;}vector<vector<int>> dp(n, vector<int>(2,0));dp[0][0] = 0;dp[0][1] = -prices[0];for(int i=1; i<n; i++){//dp[i][0],第i-1天就没有,或者第i天卖了dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i]);//dp[i][1],第i-1天没有,第i天买了dp[i][1] = max(dp[i-1][0]-prices[i], dp[i-1][1]);}return max(dp[n-1][0], dp[n-1][1]);}
};

跳跃游戏

求到达nums[n-1]的最小跳跃次数。

class Solution {
public:int jump(vector<int>& nums) {int n = nums.size();vector<int> dp(n, INT_MAX);dp[0] = 0;for(int i=0; i<n; i++){for(int j=i+1; j<=i+nums[i] && j<=n-1; j++){dp[j] = min(dp[j], dp[i]+1);}}return dp[n-1];}
};

H指数

数组citations表示研究者第i篇论文被引用的次数,计算并返回研究者的h指数。

至少发表h篇论文,至少有h篇论文被引用次数大于等于h。

class Solution {
public:int hIndex(vector<int>& citations) {int n = citations.size();int h = n;sort(citations.begin(), citations.end());while(h){int count = 0;for(int i=n-1; i>=0; i--){if(citations[i] >= h){count++;}}if(count >= h){return h;}h--;}return 0;}
};

O(1)时间插入、删除和获取随机元素

实现RandomizedSet类
变长数组+哈希表
这道题要求实现一个类,满足插入、删除和获取随机元素操作的平均时间复杂度O(1)。

变长数组和哈希表结合,变长数组中存储元素,哈希表中记录每个元素在变长数组中的下标。

class RandomizedSet {
private:vector<int> nums;unordered_map<int, int> indices;
public:RandomizedSet() {srand((unsigned)time(NULL));}bool insert(int val) {if(indices.count(val)){return false;}nums.push_back(val);indices[val] = nums.size()-1;return true;}bool remove(int val) {if(indices.count(val)){int index = indices[val];int last = nums.back();nums[index] = last;indices[last] = index;nums.pop_back();indices.erase(val);return true;}return false;}int getRandom() {int randomIndex = rand()%nums.size();return nums[randomIndex];}
};/*** Your RandomizedSet object will be instantiated and called as such:* RandomizedSet* obj = new RandomizedSet();* bool param_1 = obj->insert(val);* bool param_2 = obj->remove(val);* int param_3 = obj->getRandom();*/

除自身以外数组的乘积

要求不使用除法,并且在O(n)时间复杂度内完成
左右乘积列表
我们不必将所有数字的乘积除以给定索引处的数字得到相应的答案,而是利用索引左侧所有数字的乘积和右侧所有数字的乘积相乘得到答案。

  1. 初始化两个空数组L和R,L[i]表示左侧乘积,R[i]表示右侧乘积
class Solution {
public:vector<int> productExceptSelf(vector<int>& nums) {int n = nums.size();vector<int> res(n,1);vector<int> left(n);vector<int> right(n);left[0] = 1;right[n-1] = 1;for(int i=1; i<n; i++){left[i] = left[i-1] * nums[i-1];}for(int i=n-2; i>=0; i--){right[i] = right[i+1] *nums[i+1]; }for(int i=0; i<n; i++){res[i] = left[i]*right[i];}return res;}
};

罗马数字转整数

class Solution {
private:unordered_map <char,int> map1 = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
public:int romanToInt(string s) {int sum = 0;for(int i=0; i<s.size(); i++){char c = s[i];if(i < s.size()-1 && map1[c] < map1[s[i+1]]){sum -= map1[c];}else{sum += map1[c];}}return sum;}
};

两数之和二——输入有序数组

给你一个下标从1开始的整数数组numbers,该数组已按非递减顺序排列。
左右指针

class Solution {
public:vector<int> twoSum(vector<int>& numbers, int target) {int left = 0;int right = numbers.size()-1;while(left < right){if(numbers[left] + numbers[right] == target){return {left+1, right+1};}else if(numbers[left] + numbers[right] > target){right--;}else{left++;}}return {1,2};}
};

长度最小的子数组

给定一个含有n个正整数的数组和一个正整数target。
找出该数组中满足其总和大于等于target的长度最小的子数组,并返回长度。如果不存在符合条件的子数组,返回0。

滑动窗口
定义两个指针start和end分别表示子数组(滑动窗口的开始位置和结束位置),维护变量sum存储子数组中的元素和。

初始状态下,start和end都指向下标0,sum的值为0。

每一轮迭代,将nums[end]加到sum,如果sum≥s,则更新子数组的最小长度(此时子数组的长度是end-start+1)

给定一个含有n个正整数的数组和一个正整数target。
找出总和大于等于target的最小子数组的长度,如果没有,返回0。

class Solution{
public:int minSubArrayLen(int target, vector<int>& nums){int n = nums.size();int start = 0;int end = 0;int sum = 0;int ans = INT_MAX;while(end < n){sum += nums[end];while(sum >= target){ans = min(ans, end-start+1);sum -= nums[start];start++;}end++;}return ans==INT_MAX ? 0:ans;}
};

无重复字符的最长子串

class Solution {
public:int lengthOfLongestSubstring(string s) {unordered_set<char> set1;int start = 0;int end = 0;int n = s.size();int ans = 0;while(end < n){//如果最后一个字符不在已有的字符串中,则添加if(!set1.count(s[end])){set1.insert(s[end]);ans = max(ans, end-start+1);end++;}else{while(set1.count(s[end])){set1.erase(s[start]);start++;}}}return ans;}
};

单词规律

给定一种规律pattern和一个字符串s,判断s是否遵循相同的规律。

class Solution{
public:bool wordPattern(string pattern, string s){unordered_map<char, string> chToStr;unordered_map<string, char> strToCh;vector<string> strVector;istringstream iss(s);string word;while(iss >> word){strVector.push_back(word);}//检查长度if(pattern.size() != strVector.size()){return false;}for(int i=0; i<pattern.size(); i++){char ch = pattern[i];string str = strVector[i];//字符到字符串映射if(chToStr.count(ch)){if(chToStr[ch] != str){return false;}}else{chToStr[ch] = str;}//字符串到字符映射if(strToCh.count(str)){if(strToCh[str] != ch){return false;}}else{strToCh[str] = ch;}}return true;}
};

插入区间

给一个无重叠的,按照区间起始端点排序的区间列表intervals。

class Solution {
public:vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {vector<vector<int>> res;int n = intervals.size();int i;//前半段for(i=0; i<n; i++){if(intervals[i][1] < newInterval[0]){res.push_back(intervals[i]);}else{break;}}//中间for(i; i<n; i++){if(intervals[i][0] <= newInterval[1]){newInterval[0] = min(intervals[i][0], newInterval[0]);newInterval[1] = max(intervals[i][1], newInterval[1]);}else{break;}}res.push_back(newInterval);//尾部for(i; i<n; i++){res.push_back(intervals[i]);}return res;}
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/859947.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

react18 实现具名插槽

效果预览 技术要点 当父组件给子组件传递的 JSX 超过一个标签时&#xff0c;子组件接收到的 children 是一个数组&#xff0c;通过解析数组中各 JSX 的属性 slot &#xff0c;即可实现具名插槽的分发&#xff01; 代码实现 Father.jsx import Child from "./Child";…

【D3.js in Action 3 精译】第一部分 D3.js 基础知识

第一部分 D3.js 基础知识 欢迎来到 D3.js 的世界&#xff01;可能您已经迫不及待想要构建令人惊叹的数据可视化项目了。我们保证&#xff0c;这一目标很快就能达成&#xff01;但首先&#xff0c;我们必须确保您已经掌握了 D3.js 的基础知识。这一部分提到的概念将会在您后续的…

ModuleNotFoundError: No module named ‘src‘

一、问题: 在尝试通过命令行直接运行主脚本时&#xff0c;由于模块路径问题导致模块导入失败。 错误日志&#xff1a; [21:16:19] [~/develop/workspace/pycharm/my-app] ❱❱❱ python src/main.py Traceback (most recent call last):File "src/main.py", …

探秘神经网络激活函数:Sigmoid、Tanh和ReLU,解析非线性激活函数的神奇之处

引言 在神经网络中&#xff0c;激活函数扮演着至关重要的角色。它们赋予神经网络非线性的能力&#xff0c;使得网络具备学习和表示复杂函数关系的能力。本文将详细解析三种常见的激活函数&#xff1a;Sigmoid、Tanh和ReLU&#xff0c;揭开它们在神经网络中的奥秘。无论你是初学…

算法题day49(6.4打卡:dp08)

一、leetcode刷题&#xff1a; 1.leetcode题目 121.买卖股票的最佳时机 . - 力扣&#xff08;LeetCode&#xff09;(easy&#xff09; 解决&#xff1a; class Solution:def maxProfit(self, prices: List[int]) -> int:cur_min prices[0]maxx 0for i in range(1,len(p…

【十一】【QT开发应用】模拟腾讯会议登录界面设计UI

ui 加入会议的样式表 QPushButton { /* 前景色 */ color:#0054E6; /* 背景色 */ background-color:rgb(255,255,255); /* 边框风格 */ border-style:outset; /* 边框宽度 */ border-width:0.5px; /* 边框颜色 */ border-color:gray; /* 边框倒角 */ border-radius…

日常-----最爱的人

今日话题 大家好嗷&#xff0c;今天聊的技术可比之前的重要的多啊&#xff0c;哼哼&#xff0c;也不是今天&#xff0c;大家像我看齐嗷&#xff0c;我宣布个事情&#xff01;&#xff01;&#xff01; 于2024年6月21日晚上&#xff0c;本人遇到了这一生最爱的人 嘿嘿 这种事…

微信小程序 引入MiniProgram Design失败

这tm MiniProgramDesign 是我用过最垃圾的框架没有之一 我按照官网的指示安装居然能安装不成功,牛! 这里说明我是用js开发的 到以上步骤没有报错什么都没有,然后在引入组件的时候报错 Component is not found in path “./miniprogram _npm/vant/weapp/button/index” (using…

EPUB和MOBI两种电子书格式简介

EPUB和MOBI是两种流行的电子书格式&#xff0c;它们各自有不同的来历、优势和特点。 EPUB的来历、优势和特点24578: 来历: EPUB于2007年9月成为国际数字出版论坛&#xff08;IDPF&#xff09;的正式标准&#xff0c;目的是取代旧的Open eBook电子书标准。优势: 可移植性: 可以…

WP_Object_Cache如何使用?

WP_Object_Cache是WordPress用于缓存数据的类。每次页面载入时&#xff0c;都能够重新生成这些缓存数据。在wp-includes/cache.php文件中定义WP_Object_Cache。 编写插件时不要在代码中直接使用WP_Object_Cache&#xff0c;应使用下面列出的wp_cache函数。 默认情况下&#x…

如何优雅地处理IllegalAccessException异常?

如何优雅地处理IllegalAccessException异常&#xff1f; 大家好&#xff0c;我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01; 在Java编程中&#xff0c;IllegalAccessException异常…

Android 界面库 (一) 之 View binding 简单使用

1. 简介 在过去Android开发中&#xff0c;一般会使用 findViewById() 方法来获取 XML 布局文件中的 View 对象&#xff0c;然后对该对象进行设置文本、设置是否可见、设置点击事件回调等的视图操作。但是这种对 View 的对象获取和操作的方式会可能存在一些问题&#xff0c;例如…

大数据面试题之Zookeeper面试题

目录 1、介绍下Zookeeper是什么? 2、Zookeeper有什么作用?优缺点?有什么应用场景? 3、Zookeeper的选举策略&#xff0c;leader和follower的区别? 4、介绍下Zookeeper选举算法 5、Zookeeper的节点类型有哪些?分别作用是什么? 6、Zookeeper的节点数怎么设置比较好? …

CSS阴影优化气泡框样式

<body> <div class"pop">气泡框</div> </body>body{display: flex;justify-content: center;align-items: center;height: 100% } .pop{display: flex;justify-content: center;align-items: center;background: #409eff;width: 150px;heigh…

03-Shell编程之循环语句与函数

目录 3.1 for循环语句 3.1.1for语句的结构 3.1.2 for语句应用实例 3.2 使用whlie循环语句 1.打印数字1到5 3.3 使用until循环语句 3.3.1until的实例 1.打印数字1到5&#xff08;使用until的逆向逻辑&#xff09; 2.等待用户输入特定内容 3.4 函数 3.4.1Shell函数的基…

自学C语言-10

第10章 指针 指针是C语言的一个重要组成部分&#xff0c;是C语言的核心、精髓所在。用好指针&#xff0c;可以在C语言开发中起到事半功倍的效果。一方面&#xff0c;可以提高程序的编译效率、执行速度&#xff0c;以及动态存储分配&#xff1b;另一方面&#xff0c;可使程序更加…

代码随想录算法训练营第四十八天 | 188.买卖股票的最佳时机IV、309.最佳买卖股票时机含冷冻期、714.买卖股票的最佳时机含手续费、股票总结

188.买卖股票的最佳时机IV 题目链接&#xff1a;https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/ 文档讲解&#xff1a;https://programmercarl.com/0188.%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4… 视频讲解&#xff1a;https://www.bi…

playwright录制脚本原理

Paywright录制工具UI 在上一篇博客中介绍了如何从0构建一款具备录制UI测试的小工具。此篇博客将从源码层面上梳理playwright录制原理。当打开playwright vscode插件时&#xff0c;点击录制按钮&#xff0c;会开启一个新浏览器&#xff0c;如下图所示&#xff0c;在新开浏览器页…

python监听麦克风并调用阿里云的实时语音转文字

import time import threading import queue import sounddevice as sd import numpy as np import nls import sys# 阿里云配置信息 URL "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1" TOKEN "016ca1620aff421da8fac81b9fb52dc5" # 参考https:/…

Hive基础知识(十八):Hive 函数的使用

1. 系统内置函数 1&#xff09;查看系统自带的函数 hive (hive3)> show functions; Time taken: 0.085 seconds, Fetched: 289 row(s) 2&#xff09;显示自带的函数的用法 hive (hive3)> desc function upper; OK tab_name upper(str)- Returns str with all characters…