码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_01两数之和

时间:2020-02-15 13:07:43      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:sum   sharp   namespace   ati   str   highlight   序列   stream   name   

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

样例  

给定数组 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;
}

leetcode_01两数之和

标签:sum   sharp   namespace   ati   str   highlight   序列   stream   name   

原文地址:https://www.cnblogs.com/zhuomoyixia/p/12311141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!