LeetCoe-1. Two Sum

提交代码:
Python: HashTable
To improve our run time complexity, we need a more efficient way to check if the complement (the value) exists in the array. If the complement exists, we need to look up its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.

We reduce the look up time from O(n)O(n) to O(1)O(1) by trading space for speed. A hash table is built exactly for this purpose, it supports fast look up in near constant time. I say "near" because if a collision occurred, a look up could degenerate to O(n)O(n) time. But look up in hash table should be amortized O(1)O(1) time as long as the hash function was chosen carefully.

A simple implementation uses two iterations. In the first iteration, we add each element's value and its index to the table. Then, in the second iteration we check if each element's complement (target - nums[i]target−nums[i]) exists in the table. Beware that the complement must not be nums[i]nums[i] itself!
def twoSum(nums,target):
    hashtable = {}
    for i in range(len(nums)):
        hashtable.__setitem__(nums[i],i)
    for i in range(len(nums)):
        complement = target - nums[i]
        if hashtable.__contains__(complement) and hashtable.get(complement)!=i:
            return (i,hashtable.get(complement))
if __name__ == "__main__":
    nums = [2, 7, 11, 15, 11, 2 , 4]
    target = 9
    print(twoSum(nums,target))




C++
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    for(int i=0;i<nums.size();++i){
        for(int j=i+1;j<nums.size();j++){
            if(nums[j]+nums[i]==target){
                vector<int> ret{i,j};
                return ret;
            }
        }
    }
        return vector<int>{0,0};
    }
};
JAVA
class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i=0;i<nums.length;++i){
            for(int j=i+1;j<nums.length;++j){
                if(nums[i]+nums[j]==target)
                    return new int []{i,j};
            }
        }
        throw new IllegalArgumentException("No two sum solution");//这个是不能少的
 }
}
JAVA大鸟写法:

class Solution {
     public int[] twoSum(int[] nums, int target) {
         Map<Integer, Integer>map=new HashMap<>();
         for(int i=0;i<nums.length;++i)
             map.put(nums[i],i);
         for(int i=0;i<nums.length;++i){
             int complement=target-nums[i];
             //boolean containsKey(Object k)
             //如果此映射包含指定键的映射关系,则返回 true。
             
             
             //Object get(Object k)
             //返回指定键所映射的值;如果此映射不包含该键的映射关系,则返回 null。
            if(map.containsKey(complement)&&map.get(complement)!=i){
                 return new int[]{i, map.get(complement)};
             }      
         }
         throw new IllegalArgumentException("No two sum solution");
 }
}
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n,m=0;
        vector<int>res;
        for(n=0;n<nums.size();++n){
            for(m=n+1;m<nums.size();++m)
                if(nums[m]+nums[n]==target){
                    res.push_back(n);
                    res.push_back(m);
                    return res;
                }  
        }
        return res;
    }
};

python 暴力
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        res=[]
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j]==target:
                    res.append(i)
                    res.append(j)
                    return res
      

#include<string.h>
#include
#include
#include<bits/stdc++.h>
using namespace std;
bool compare(vector a,vector b){
return a<b;
}
int main(){
vectorobj;//创建一个向量存储容器int
for(int i=0;i<10;i++){//push_back(elem)在数组最后添加数据
obj.push_back(i);
cout<<obj[i]<<",";
}
for(int i=0;i<5;i++){//去掉数据最后一个数据
obj.pop_back();
}
cout<<endl;
for(int i=0;i<obj.size();i++)//size()容器中实际数据个数
cout<<obj[i]<<",";
obj.clear();//清楚容器中所有的数据
cout<<endl;
cout<<“obj.size()=”+obj.size()<<endl;

obj.push_back(1);
obj.push_back(3);
obj.push_back(0);
sort(obj.begin(),obj.end());//从小到大
for(int i=0;i<obj.size();++i)
cout<<obj[i]<<",";
cout<<endl;
cout<<"从大到小:"<<endl;
reverse(obj.begin(),obj.end());//从大到小
for(int i=0;i<obj.size();++i)
cout<<obj[i]<<","; 

//sort(obj,obj+obj.size(),compare);

for(int i=0;i<obj.size();++i)
cout<<obj[i]<<",";
cout<<endl;
//方法二,使用迭代器将容器中数据输出 
vector<int>::iterator it;//声明一个迭代器,来访问vector容器,作用:遍历或者指向vector容器的元素 
for(it=obj.begin();it!=obj.end();it++)
{
    cout<<*it<<" ";
}

int N=5, M=6; 
vector<vector<int> > obj1(N, vector<int>(M)); //定义二维动态数组5行6列 

for(int i=0; i< obj1.size(); i++)//输出二维动态数组 
{
    for(int j=0;j<obj1[i].size();j++)
    {
        cout<<obj1[i][j]<<" ";
    }
    cout<<"\n";
}

return 0;

}

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.m或d论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 、1资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值