LeetCode-1 Two Sum

问题链接

C++

class Solution 
{
    public:
        vector<int> twoSum(vector<int>& nums, int target) 
        {
            int ok = 0;
            vector<int> res;
            for (int i = 0; !ok && i < nums.size(); ++i)
            {
                for (int j = i + 1; !ok && j < nums.size(); ++j)
                {
                    if (nums[i] + nums[j] == target)
                    {
                        ok = 1;
                        res.push_back(i);
                        res.push_back(j);
                    }
                }
            }
            return res;
        }
};

Python

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        res = []
        for i in range(0, len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    res.append(i)
                    res.append(j)
                    return res
        

猜你喜欢

转载自blog.csdn.net/qq_30986521/article/details/80695199
今日推荐