zoukankan      html  css  js  c++  java
  • LeetCode_Two Sum

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9

    Output: index1=1, index2=2 

    参见《编程之美》2.12快速寻找满足条件的两个数。这里采用的解法2中的hash表,采用C++中的map容器,以数组元素为key,因为要返回下标,以下标为value。算法时间复杂度O(n),空间复杂度O(n).

    代码(AC):

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
        map<int,int> map1;//<数值,下标> 
        vector<int> vin;
        
        int len = numbers.size();
        //cout<<len<<endl;
        for(int i = 0;i<len;i++)
        {
                map1[numbers[i]] = i;
        }
        for(int i = 0;i<len;i++)
        {
                int sum = target - numbers[i];
                map<int,int>::iterator it = map1.end();
                if(it != map1.find(sum)&&map1.find(sum)->second!=i)
                {
                      
                      vin.push_back(i+1);
                      vin.push_back(map1.find(sum)->second+1);
                     
                }
        } 
        return vin;
        }
    };
    如果不要求返回符合条件元素在原数组的下标,《编程之美》中的解法三很巧妙。如果已经了这个数组任意两个元素之和的有序数组,那么采取Binary Search,在O(logN)时间内就可以解决问题。但是计算每两个元素和的有序数组需要O(n^2),我们并不需要求解这个数组。这个思考启发我们,可以直接对两个数字的和进行有序遍历,降低时间复杂度。

    首选,对原数组进行排序,采用Qsort,时间复杂度O(NlogN);

    声明两个下标,i = 0;j = n-1;比较array[i]+array[j]是否等于target,如果是返回array[i]和array[j],若小于target,则i++;如果大于target,则

    j--;遍历一次即可。时间复杂度O(n).所以该方法的时间复杂度是O(n)+O(NlogN) = O(NlogN)。要是题目返回原始数组的下标,则在对原数组排序的时候要保存各个元素在原数组的下标。

    伪代码:

    Qsort(array);

    for (i=0,j=n-1;i<j)

    if(array[i]+array[j]==target) return (array[i],array[j]);

    else if(array[i]+array[j]<target) i++;

    else j--;

    return ;




  • 相关阅读:
    微软WP7本地数据库之Sqlite编程技巧(转)
    AutoResetEvent详解
    桥接模式的简单分析
    解决VS2008 调试启动特别慢
    软件概要设计
    解决windows8不能安装ZUNE的问题
    CDATA的对特殊字符作用说明
    DataTable对象在内存中的使用(二)
    DataTable对象在内存中的使用(一)
    关于MVC3 CODE FIRST的安装
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601442.html
Copyright © 2011-2022 走看看