LeetCoe-1. Two Sum

版权声明:流浪者 https://blog.csdn.net/gz153016/article/details/85787106
提交代码:
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;

}

猜你喜欢

转载自blog.csdn.net/gz153016/article/details/85787106