leetcode_01两数之和

题目描述
给定一个整型数组,要求返回两个数的下标,使得两数之和等于给定的目标值,要求同一个下标不能使用两次。
数据保证有且仅有一组解。

样例  

给定数组 nums = [2, 7, 11, 15],以及目标值 target = 9,
由于 nums[0] + nums[1] = 2 + 7 = 9,
所以 return [0, 1]. 

思路一

暴力破解

代码

#include <iostream>
using namespace std;

class Solution {
public:
    int* twoSum(const int nums[], int size, int target) {
        int static result[2];
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                if (nums[j] == target - nums[i]) {
                    result[0] = i;//把数组中的序列存到新的数组result中
                    result[1] = j;
                    return result;//返回的是数组result
                    // return result[] { i, j };
                }
            }
        }
    }
};
int main() {
    Solution solute;//类 对象
    int nums[] = { 2, 7, 11, 15 };
    int value = 9;
    int size = sizeof(nums) / 4;//sizeof得到数组大小
    int* result = solute.twoSum(nums, size, value);//调用对象的属性:数组
    cout << result[0] << endl;
    cout << result[1] << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhuomoyixia/p/12311141.html