LeetCode 1. Sum of Two Numbers [Array + Hash Table] C++ and Java Edition Problem Solutions

LeetCode 1. The sum of two numbers

Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array and return their array subscripts.

You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice.

Example:
Given nums = [2, 7, 11, 15], target = 9

Because nums[0] + nums[1] = 2 + 7 = 9

So return [0, 1]

C++ code

Plain version, Double for loop, time complexity is O(n^2)

class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& nums, int target)
    {
    
    
    vector<int>res;
    for(int i=0;i<nums.size();i++)
    {
    
    
        for(int j=0;j<i;j++)
        {
    
    
            if(nums[i]+nums[j]==target)
            {
    
    
                res={
    
    j,i};  //记录答案
                break;
            }
        }
        if(res.size()>0) break;
    }    
    return res;
    }
};

Optimized version
Use unordered<int,int>hash; Use hash table to optimize, establish key (element) to value (subscript) mapping. The time complexity is O(n).

class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& nums, int target)
    {
    
    
        vector<int>res;
        unordered_map<int,int>hash;
        for(int i=0;i<nums.size();i++)
        {
    
    
            int another=target-nums[i];
            if(hash.count(another))
            {
    
    
               res=vector<int>{
    
    hash[another],i};
               break;
            }
            hash[nums[i]]=i;
        }
        return res;
    }
};
Java Edition
class Solution 
{
    
    
    public int[] twoSum(int[] nums, int target) 
   {
    
    
        HashMap< Integer,Integer>hash = new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++)
        {
    
    
            int another =target-nums[i];
            if(hash.containsKey(another))    //查找key值
            {
    
    
                return new int[]{
    
    hash.get(another),i};  //找到了直接返回
            }
            hash.put(nums[i],i);
        }
        return new int[]{
    
    -1,-1};
    }
}

The arrangement of unordered_map will be given later.

Guess you like

Origin blog.csdn.net/weixin_45629285/article/details/109542829