• [每日一题2020.06.13]leetcode #739 #15 单调栈 双指针查找


    739 每日温度 ( 单调栈 )

    题目 : https://leetcode-cn.com/problems/daily-temperatures/

    题意 : 找到数组每一个元素之后第一个大于它的元素的位置

    思路 : 从后往前遍历数组, 进行压栈操作, 栈中保留元素在T中的索引, 栈始终呈下大上小的状态, 对于每个遍历到的元素如果小于栈顶则输出1, 如果大于栈顶则把栈顶元素弹出知道匹配到小于的元素

    核心 : 维护一个单调递减栈

    ( 忘记存代码了, 嫖一份算了

    class Solution {
    public:
        vector<int> dailyTemperatures(vector<int>& T) {
            vector<int> ans(T.size());
            stack<int> s;
            for (int i = 0; i < T.size(); ++i) {
                while (!s.empty() && T[i] > T[s.top()]) {
                    int temp = s.top();
                    ans[temp] = i - temp;
                    s.pop();
                }
                s.push(i);
            }
            return ans;
        }
    };
    

    15 三数之和 双指针查找

    题意 : 给一个数组找出数组中所有a+b+c = 0的元素组合, 注意避免重复

    题目 : https://leetcode-cn.com/problems/3sum/

    思路 : 先sort, 然后查找 : a元素从头开始遍历, b和c用两个指针前后双指针查找, 复杂度O((N^2))

    容易出错的点 :

    • 避免重复的过程中, 出现指针越界的现象的判定
    • 压入数组的时间
    • 当a+b+c==0后对两指针的操作时指针越界的判定

    反正我交了5发, 问题都是靠特判解决的, 这种题还是要多列几种情况再动手

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
        vector<vector<int> > threeSum(vector<int>& nums) {
    	 vector< vector<int> > ans;
    	 vector<int> tmp(3);
    	 sort(nums.begin(), nums.end());
    	 for (unsigned int i = 0; i < nums.size(); ++i)
    	 {	
    	 	if(i != 0)
    	 		while(nums[i]==nums[i-1] && i < nums.size()-2)++i;
    	 	if(nums[i] > 0 || i>=nums.size()-2) break;
    	 	int a = nums[i];
    	 	int l = i+1, r = nums.size() - 1;
    	 	while(l < r) {
    		 	if(a + nums[l] + nums[r] == 0) {
    		 		tmp[0] = a, tmp[1] = nums[l], tmp[2] = nums[r];
    		 		l++;r--;
    		 		while(nums[l]==nums[l-1] && l<r)l++;
    		 		while(nums[r]==nums[r+1] && l<r)r--;
    	 		}	
    		 		ans.push_back(tmp);
    	 		else{
    	 			if(nums[l] + a < -nums[r])
    		 			l++;
    			 	else
    			 		r--;
    	 		}
    	 	}
    
    	 }
    	 return ans;
    }
    
    
    int main(){
    	ios::sync_with_stdio(false);
        cin.tie(0);
        int a[6] = {3, 0, -2, -1, 1, 2};
    	vector<int> num(a, a+6);
        vector< vector<int> > s = threeSum(num);
        for(unsigned int i = 0; i < s.size(); ++i) {
        	for(int j = 0; j < 3; ++j) {
        		cout << s[i][j] << " ";
        	}
        	cout << endl;
        }
    	return 0;
    }
    
  • 相关阅读:
    Ubuntu 16 编译装python2.7
    配置ubunto 流量使用限制 python 实现简单 http server
    vnstat 流量统计 并附带一个小 php 查看流量的页面
    ubunto 免输入密码 登录 putty ssh-keygen
    nes 红白机模拟器 第5篇 全屏显示
    arm 添加 samb 文件共享
    arm 添加 ftp server 之 bftpd
    Tga图片格式分析以及程序实现
    领导力:刘邦的管理之道
    AS3:辨析ROLL_OVER与MOUSE_OVER,ROLL_OUT与MOUSE_OUT
  • 原文地址:https://www.cnblogs.com/roccoshi/p/13099299.html
Copyright © 2020-2023  润新知