当前位置:网站首页>只出现一次的数字<难度系数>&& 杨辉三角<难度系数>
只出现一次的数字<难度系数>&& 杨辉三角<难度系数>
2022-06-23 10:22:00 【华为云】
1、只出现一次的数字<难度系数>
题述:给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗 ?
示例1:
输入: [2,2,1]
输出: 1
示例2:
输入: [4,1,2,1,2]
输出: 4
🧷 平台:Visual studio 2017 && windows
核心思想:使用异或操作符 ^ —— 相同为 0,相异为 1
class Solution {public: int singleNumber(vector<int>& nums) { int ret = 0; //1、operator[] /*for(size_t i = 0; i < nums.size(); ++i) { ret ^= nums[i]; }*/ //2、迭代器 /*vector<int>::iterator it = nums.begin(); while(it != nums.end()) { ret ^= *it; ++it; }*/ //3、范围for for(auto e : nums) { ret ^= e; } return ret; }};2、杨辉三角<难度系数>
题述:给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。在「杨辉三角」中,每个数是它左上方和右上方的数的和。

示例1:
输入:numRows = 5
输出:[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
示例2:
输入:numRows = 1
输出:[ [1] ]
提示:1 <= numRows <= 30
🧷 平台:Visual studio 2017 && windows
核心思想:需要先生成一个杨辉三角,每行的第一个和最后一个是 1,其余设置为 0,如果是 0,则需要计算。这里可以发现规律:1 = 1 + (1 - 1),这里以第一个要计算的值为例,且这里的数字代表的下标 —— 第 3 行以 1 为下标位置的值是等于第 2 行以 1 为下标的值加上第 2 行以 1 - 1 为下标的值。
class Solution {public: //vector<vector<int>>就是一个二维数组,这里在vector模拟实现的时候也会细讲 vector<vector<int>> generate(int numRows) { vector<vector<int>> vv; vv.resize(numRows); //生成 for(size_t i = 0; i < vv.size(); ++i) { //每行有多少个,并初始化为0 vv[i].resize(i + 1, 0); //每一行的第一个和最后一个赋值为1 /*vv[i].front() = 1; vv[i].back() = 1;*/ vv[i][0] = 1; vv[i][vv[i].size() - 1] = 1; } //遍历 for(size_t i = 0; i < vv.size(); ++i) { for(size_t j = 0; j < vv[i].size(); ++j) { if(vv[i][j] == 0)//需要处理 { vv[i][j] = vv[i - 1][j] + vv[i - 1][j - 1]; } } } return vv; }};补充
这道题如果是用 C语言去写的话,就要动态开辟一个二维数组,写起来相对没有 C++ 的舒服。
边栏推荐
- Set up a QQ robot for ordering songs, and watch beautiful women
- Noi OJ 1.3 05: floating point numeric C language for calculating fractions
- 六张图详解LinkedList 源码解析
- MySQL-02.工作中对索引的理解
- NFS挂载时一直没有同步文件
- How to solve the problem that easycvr does not display the interface when RTMP streaming is used?
- Spring recruitment interview experience summary (technical post)
- How does thymeleaf get the value of the request parameter in the URL?
- 一个优秀速开发框架是什么样的?
- 用贪吃蛇小游戏表白(附源码)
猜你喜欢
随机推荐
2021-04-16数组
Five SQL functions for operation date that must be known in SQL tutorial
【软件与系统安全】堆溢出
Golang 快速上手 (2)
解决预览pdf不能下载的问题
Noi OJ 1.3 16: calculating segment length C language
NOI OJ 1.3 20:计算2的幂 C语言
当 Pandas 遇见 SQL,一个强大的工具库诞生了
Noi OJ 1.2 conversion between integer and Boolean C language
2021-05-11instanceof和类型转换
马斯克 18 岁儿子请愿改名,欲断绝父子关系
Too helpless! Microsoft stopped selling AI emotion recognition and other technologies, saying frankly: "the law can not keep up with the development of AI"
Solve the problem of invalid audio autoplay
Unity技术手册 - 生命周期LifetimebyEmitterSpeed-周期内颜色ColorOverLifetime-速度颜色ColorBySpeed
2021-05-12接口的定义与实现
数值计算方法
Unity technical manual - shape sub module - Sprite, spriterenderer and velocity over lifetime
Mathematical analysis_ Notes_ Chapter 2: real and plural numbers
Google Earth Engine(GEE)——用不同方法计算slope对比案例分析
2021-05-11 static keyword








