leetcode5.10

1.找出只出现一次的数字

要求:线性时间复杂度->位运算

用到的性质:

任何数和 0 做异或运算,结果仍然是原来的数
任何数和其自身做异或运算,结果是 0
异或运算满足交换律和结合律。

int singleNumber(vector<int>& nums) {
     int res=0;
     for(auto e:nums){
         res^=e;

     }
     return res;

    }

2.找到多数元素

用到:哈希表

注意:return不能不够

int majorityElement(vector<int>& nums) {
        int n=nums.size();
        int m=n/2;
        map<int,int>mmap;
        for(auto e:nums){
            mmap[e]+=1;
            if(mmap[e]>m)return e;
        }
        
        return -1;
        

    }

3.三数之和

思想:排序+双指针,夹紧范围

细节:为了时间复杂度小一点,要避免做很多重复的工作。比如保证c比b大,那后面如果不符合要求,改变c(往回)就好了

vector<vector<int>> threeSum(vector<int>& nums) {
        int n=nums.size();
        sort(nums.begin(),nums.end());
        vector<vector<int>>ans;
        for (int first = 0; first < n; ++first) {
      
            //必须得有小于0的,排好序以后肯定在前面呢
            if(first>0&&nums[first]==nums[first-1]){
                continue;
            }

            // c 对应的指针初始指向数组的最右端,作为最大的那个数
            int third=n-1;
            int target=-nums[first];
            
            // 枚举 b
            for (int second = first + 1; second < n; ++second) {
                // 必须得在first的后边并且不能重复
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                // 需要保证 b 的指针在 c 的指针的左侧,如果有问题就出在c上
                while (second < third && nums[second] + nums[third] > target) {
                    --third;
                }
                // 如果指针重合,随着 b 后续的增加
                // 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
                if (second == third) {
                    break;
                }
                if (nums[second] + nums[third] == target) {
                    ans.push_back({nums[first], nums[second], nums[third]});
                }
            }

        }
        return ans;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值