7. 杨辉三角(简单)
题目要求:
给定一个非负整数numRows
,生成杨辉三角
的前numRows
行。
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
#include <string>
class Solution
{
public:
vector<vector<int>> generate(int numRows)
{
vector<vector<int>> ret(numRows); // 创建一个嵌套vector存放每一层的数据
for (int i = 0; i < numRows; i++)
{
ret[i].resize(i + 1); // 设置第i+1层的空间
ret[i][0] = ret[i][i] = 1; // 设置每层的第一个元素和最后一个元素为1
for (int j = 1; j < i; j++) // 遍历每层的除第一个元素和最后一个元素的其它元素
{
ret[i][j] = ret[i - 1][j] + ret[i - 1][j - 1]; // 该层元素的值为上层两个元素之和
}
}
return ret;
}
};
int main()
{
int a = 4;
vector<vector<int>> ret;
Solution s;
ret = s.generate(a);
// 嵌套容器的遍历
for (vector<vector<int>>::iterator it = ret.begin(); it != ret.end(); it++)
{
for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++)
{
cout << *vit << " ";
}
cout << endl;
}
system("pause");
return 0;
}
8. 杨辉三角II(简单)
题目要求:
给定一个非负索引rowIndex
,返回杨辉三角
的第rowIndex
行。
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
#include <string>
class Solution
{
public:
vector<int> getRow(int rowIndex)
{
vector<vector<int>> ret(rowIndex); // 创建一个嵌套vector存放每一层的数据
for (int i = 0; i < rowIndex; i++)
{
ret[i].resize(i + 1); // 设置第i+1层的空间
ret[i][0] = ret[i][i] = 1; // 设置每层的第一个元素和最后一个元素为1
for (int j = 1; j < i; j++) // 遍历每层的除第一个元素和最后一个元素的其它元素
{
ret[i][j] = ret[i - 1][j] + ret[i - 1][j - 1]; // 该层元素的值为上层两个元素之和
}
}
return ret[rowIndex - 1]; // 生成一个行数为rowIndex的杨辉三角,然后取出其最后一行
}
};
int main()
{
int rowIndex = 4;
vector<int> ret;
Solution s;
ret = s.getRow(rowIndex);
for (vector<int>::iterator it = ret.begin(); it != ret.end(); it++)
{
cout << *it << " ";
}
cout << endl;
system("pause");
return 0;
}
9. 只出现一次的数字(简单)(重要)
题目要求:
给你一个 非空 整数数组nums
,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次
的元素。
必须设计并实现线性时间复杂度的算法来解决此问题,且该算法只使用常量额外空间。
题目分析:
使用位运算异或
。
异或有如下性质:
a
⊕
a
=
0
,
a
⊕
0
=
a
a
⊕
b
⊕
c
=
a
⊕
c
⊕
b
=
b
⊕
a
⊕
c
a\oplus a=0,a\oplus 0=a \\ a\oplus b\oplus c=a\oplus c\oplus b=b\oplus a\oplus c
a⊕a=0,a⊕0=aa⊕b⊕c=a⊕c⊕b=b⊕a⊕c
因此,题目中描述的数组可以表示为[a,a,b,b,c,c,d],将其每个元素按位异或后的结果显然为d,即数组中只出现一次的数。
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
#include <string>
class Solution
{
public:
int singleNumber(vector<int>& nums)
{
int ret = 0;
for (auto e : nums) // 相当于for (vector<int>::iterator it = ret.begin(); it != ret.end(); it++)
{
ret ^= e; // 将ret和vector中每个元素异或后的值赋给ret
}
return ret;
}
};
int main()
{
vector<int> nums = { 4, 1, 2, 1, 2 };
Solution s;
int ret = s.singleNumber(nums);
cout << "给定数组中只出现一次的数为:" << ret << endl;
system("pause");
return 0;
}