[LeetCode] [C++] 1. 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, and you may not use the same element twice.

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

問題描述


給定一個數字和一個目標數字,求出數組中兩個數字之和等於給定的目標數字。
注意:假定每個數組中有且只有一組解,不能使用同一個數組元素兩次

例如:數組[2,7,11,15], 目標數字9,因為nums[0] + nums[1] = 9,所以返回[0,1]

思路分析


遍歷數組法,直接遍歷整個數組,找到兩個數組元素和等於target即可

代碼驗證

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

總結注意


注意跳出內外循環的條件
內外循環兩次遍歷時找到對應的數組元素和為target后退出內層循環,再在外層循環
檢測ret中是否有元素,如果有元素直接跳出循環檢測。

原創聲明


作者:hgli_00
鏈接:http://www.cnblogs.com/lihuagang/p/leetcode_1.html
來源:博客園
著作權歸作者所有,轉載請聯系作者獲得授權。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM