Two Sum

    xiaoxiao2023-03-24  2

    问题描述

    LeetCode - Two Sum Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution.

    Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

    给定一个整型数组,找到数组内的两个数使得两者之和等于给定的target值,返回定义的下标。假设每个输入都有唯一的输出结果。

    解决方案

    直接遍历数组,直到找到结果。(我采用的方案,毕竟第一题,所以没想太多)

    class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int i,j; bool find = false; for(i = 0;i < nums.size();i++) { for(j = i + 1;j < nums.size();j++) if(nums[i] + nums[j] == target) { find = true; break; } if(find) break; } vector<int>ret; ret.push_back(i); ret.push_back(j); return ret; } };
    转载请注明原文地址: https://ju.6miu.com/read-1200254.html
    最新回复(0)