算法——Week 1

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,


解题思路
本题是在数组中找到两个和为目标值的数,并返回其索引。首先从数组位置i开始,从0之后开始查找目标值target - array[i]是否存在,若存在,则记录下当前两个数的位置i和j, 由于array[i] + array[j] = target,即可得到解。


代码如下

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        int size = nums.size();
        int* array = new int[size];
        for(int i = 0; i < size; i++)
            array[i] = nums.at(i);
        for (int i = 0; i < size; i++) {
            int key = target - array[i]; 
            int j = 0;
            for(j = i + 1; j < size; j++) {
                if(array[j] == key) {
                    break;
                }
            }
            if (j != size) {
                result.push_back(i);
                result.push_back(j);
                break;
            }   
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/melwx/article/details/82555874