class Solution {
public:intduplicateInArray(vector<int>& nums){
int n = nums.size();//超过数据范围,无效for(auto x : nums)if(x <0|| x >= n)return-1;for(int i =0; i < n; i++){
//如果当前坐标上的m和坐标不同,而且m坐标上的数也不等于m,则交换while(i != nums[i]&& nums[i]!= nums[nums[i]])swap(nums[i], nums[nums[i]]);//如果当前坑与萝卜不匹配,且属于萝卜的坑已经有萝卜了则为重复萝卜if(nums[i]!= i && nums[nums[i]]== nums[i])return nums[i];}return-1;}};
题目二:不修改数组找出重复的数字
class Solution {
public:intduplicateInArray(vector<int>& nums){
int l =1, r = nums.size()-1;//利用抽屉原理,把长度分成两份,有一份一定会多出来while(l < r){
int mid = l + r >>1;int s =0;//统计区间[l, mid]中的数字for(auto x : nums) s += x >= l && x <= mid;if(s > mid - l +1) r = mid;else l = mid +1;}return r;}};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int>printListReversingly(ListNode* head){
vector<int> res;while(head){
res.push_back(head->val);
head = head->next;}//类似栈,利用栈的性质return vector<int>(res.rbegin(), res.rend());}};
面试题7:重建二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
map<int,int> hash;
vector<int> preorder, inorder;
TreeNode*buildTree(vector<int>& _preorder, vector<int>& _inorder){
preorder = _preorder, inorder = _inorder;//记录根节点在中序中的位置for(int i =0; i < inorder.size(); i++) hash[inorder[i]]= i;returndfs(0, preorder.size()-1,0, inorder.size()-1);}
TreeNode*dfs(int pl,int pr,int il,int ir){
if(pl > pr)return nullptr;auto root = new TreeNode(preorder[pl]);//找到位置int k = hash[root->val];//递归左边的树auto left =dfs(pl +1, pl + k - il, il, k -1);//递归右边的树auto right =dfs(pl + k - il +1, pr, k +1, ir);
root->left = left;
root->right = right;return root;}};
面试题8:二叉树的下一个节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode *father;
* TreeNode(int x) : val(x), left(NULL), right(NULL), father(NULL) {}
* };
*/
class Solution {
public:
TreeNode*inorderSuccessor(TreeNode* p){
//分为两种情况if(p->right){
p = p->right;while(p->left) p = p->left;return p;}while(p->father && p == p->father->right) p = p->father;return p->father;}};
面试题9:用两个栈实现队列
class MyQueue {
public://利用两个栈/** Initialize your data structure here. */
stack<int> stk, cache;MyQueue(){
}/** Push element x to the back of queue. */voidpush(int x){
stk.push(x);}voidcopy(stack<int>&a, stack<int>&b){
while(a.size()){
b.push(a.top());
a.pop();}}/** Removes the element from in front of queue and returns that element. */intpop(){
copy(stk, cache);int res = cache.top();
cache.pop();copy(cache, stk);return res;}/** Get the front element. */intpeek(){
copy(stk, cache);int res = cache.top();copy(cache, stk);return res;}/** Returns whether the queue is empty. */
bool empty(){
return stk.empty();}};/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
面试题10:斐波那契数列
class Solution {
public:intFibonacci(int n){
int a =0, b =1;while(n--){
int c = a + b;
a = b, b = c;}return a;}};
面试题11:旋转数组的最小数字
class Solution {
public:intfindMin(vector<int>& nums){
//二分int n = nums.size()-1;if(n <0)return-1;//去除重复数字while(n >0&& nums[n]== nums[0])n--;if(nums[n]> nums[0])return nums[0];int l =0, r = n;while(l < r){
int mid = l + r >>1;if(nums[mid]< nums[0]) r = mid;else l = mid +1;}return nums[r];}};
面试题12:矩阵中的路径
class Solution {
public:
bool hasPath(vector<vector<char>>& matrix, string str){
for(int i =0; i < matrix.size(); i ++)for(int j =0; j < matrix[i].size(); j ++)if(dfs(matrix, str,0, i, j))return true;return false;}
bool dfs(vector<vector<char>>&matrix, string &str,int u,int x,int y){
if(matrix[x][y]!= str[u])return false;if(u == str.size()-1)return true;int dx[4]={
-1,0,1,0}, dy[4]={
0,1,0,-1};char t = matrix[x][y];
matrix[x][y]='*';for(int i =0; i <4; i ++){
int a = x + dx[i], b = y + dy[i];if(a >=0&& a < matrix.size()&& b >=0&& b < matrix[a].size()){
if(dfs(matrix, str, u +1, a, b))return true;}}
matrix[x][y]= t;return false;}};
面试题13:机器人的运动范围
class Solution {
public:intget_single_sum(int x){
int s =0;while(x) s += x %10, x /=10;return s;}intget_sum(pair<int,int> p){
returnget_single_sum(p.first)+get_single_sum(p.second);}intmovingCount(int threshold,int rows,int cols){
int res =0;//判断边界条件if(!rows ||!cols)return0;
vector<vector<bool>>st(rows, vector<bool>(cols));
queue<pair<int,int>> q;//首先放入起点
q.push({
0,0});//四个方向int dx[4]={
-1,0,1,0};int dy[4]={
0,1,0,-1};while(q.size()){
auto t = q.front();
q.pop();//判断是否超出条件if(get_sum(t)> threshold || st[t.first][t.second])continue;//统计结果
res++;
st[t.first][t.second]= true;//没有超过就加入边界for(int i =0; i <4; i++){
int x = t.first + dx[i];int y = t.second + dy[i];if(x >=0&& x < rows && y >=0&& y < cols){
q.push({
x, y});}}}return res;}};
面试题14:剪绳子
class Solution {
public:intmaxProductAfterCutting(int n){
if(n <=3)return1*(n -1);//尽可能的取3int res =1;if(n %3==1) res *=4, n -=4;if(n %3==2) res *=2, n -=2;while(n) res *=3, n -=3;return res;}};
面试题15:二进制中1的个数
class Solution {
public:intNumberOf1(int _n){
//防止补码的形式unsignedint n = _n;int s =0;while(n) s += n &1, n >>=1;return s;}};
面试题16:数值的整数次方
class Solution {
public:doublePower(double base,int exponent){
double res =1;for(int i =0; i <abs(exponent); i++) res *= base;if(exponent <0) res =1/ res;return res;}};
面试题18:删除链表的节点
题目一:在O(1)时间删除链表结点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public: