【Leetcode】【Two Sum】【两数之和】【C++】

  • 题目:给定一个整型数组,返回两个数的索引,这两个数的和为给定值。
  • 说明:输入仅且仅有一个答案,且数组元素无重复。
  • 思路:两个for循环,暴力求解满足“和为给定值”的两个数的索引,复杂度为O(N2)。
  • code(C++):
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int>res;
            int len=nums.size();
            for(int i=0;i<len;i++)
            {
                for(int j=i+1;j<len;j++)
                {
                    if((nums[i]+nums[j])==target)
                    {
                        res.push_back(i);
                        res.push_back(j);
                        return res;
                    }
                }
            }
            
        }
    };

猜你喜欢

转载自www.cnblogs.com/dreamer123/p/9153519.html
今日推荐