9. Two Sum

Description

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].


Solution

 1     vector<int> twoSum(vector<int>& nums, int target) {
 2         int i,j;
 3         
 4         // Loop for the first item in the array.
 5         for ( i=0; i<nums.size(); i++){
 6             // Loop for the second item after the first item.
 7             for ( j=i; j<nums.size(); j++){
 8                 // Check if the sum equals to target.
 9                 if( (nums[i] + nums[j]) == target ){
10                     return {i,j};
11                 }       
12             }
13         }
14         
15         return {-1,-1};
16     }

猜你喜欢

转载自www.cnblogs.com/jjlovezz/p/10280743.html
今日推荐