剑指 Offer II 006. 排序数组中两个数字之和

2022/3/29 6:28:15

本文主要是介绍剑指 Offer II 006. 排序数组中两个数字之和,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

水题,vis记录,暴力即可

注意有重复

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int len = numbers.size();
        int vis[3001];
        memset(vis, 0, sizeof(vis));
        for(int i = 0; i < len; i++)
        {
            if(numbers[i] < 0)
            {
                int temp = abs(numbers[i]);
                if(vis[temp] == 0) vis[temp] = 2;
                else if(vis[temp] == 1) vis[temp] = 3;
                else if(vis[temp] == 2) vis[temp] = 4;
            }
            else
            {
                int temp = numbers[i];
                if(vis[temp] == 0) vis[temp] = 1;
                else if(vis[temp] == 2) vis[temp] = 3;
                else if(vis[temp] == 1) vis[temp] = 5;
            }
        }
        vector<int> ret;
        int flag = 0, k;
        for(int i = 0; i < len; i++)
        {
            int d = target - numbers[i];
            if(d == numbers[i])
            {
                if(d < 0 && vis[-d] == 4) ret.push_back(i);
                if(d >= 0 && vis[d] == 5) ret.push_back(i);
            }
            else if(d < 0)
            {
                d = -d;
                if(vis[d] == 2 || vis[d] == 3)
                {
                    ret.push_back(i);
                }
            }
            else
            {
                if(vis[d] == 1 || vis[d] == 3)
                {
                    ret.push_back(i);
                }
            }

        }
        return ret;

    }
};

 



这篇关于剑指 Offer II 006. 排序数组中两个数字之和的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程