• [array] leetCode-1-Two Sum-Easy


    leetCode-1-Two Sum-Easy

    descrition

    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,
    return [0, 1].
    
    

    解析

    • 方法 1 : 2 重循环去检查两个数的和是否等于 target。时间复杂度-O(n^2),空间复杂度 O(1)
    • 方法 2 : 以空间换时间,使用 hash 表存储已访问过的数,实际上是省去了方法 1 中内层循环的查找时间,时间复杂度 O(n),空间复杂度 O(n)

    注意:题目的假设,输入保证有且只有一个解;返回的是下标

    code

    
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <unordered_map>
    
    using namespace std;
    
    class Solution{
    public:
    	vector<int> twoSum(vector<int>& nums, int target){
    		return twoSumByMap(nums, target);
    	}
    
    	// time-O(n), space-O(n)
    	vector<int> twoSumByMap(vector<int>& nums, int target){
    		vector<int> ans;
    		unordered_map<int, int> hash; // <num, index>
    		for(int i=0; i<nums.size(); i++){
    			int another = target - nums[i];
    			if(hash.find(another) != hash.end()){
    				// then complexity of unordered_map.find() is 
    				// average case: constant
    				// worst case: linear in container size
    				ans.push_back(hash[another]);
    				ans.push_back(i);
    				return ans;
    			}
    			hash[nums[i]] = i;
    		}
    
    		return ans;
    	}
    
    };
    
    int main()
    {
    	freopen("in.txt", "r", stdin);
    	vector<int> nums;
    	int target;
    	int cur;
    	cin >> target;
    	while(cin >> cur){
    		nums.push_back(cur);
    	}
    	vector<int> ans = Solution().twoSum(nums, target);
    	if(!ans.empty())
    		cout << ans[0] << " " << ans[1] << endl;
    	else
    		cout << "no answer" << endl;
    
    	fclose(stdin);
    
    	return 0;
    }
    
    
  • 相关阅读:
    java集合源码
    数据库表链接的几种方式
    面试题(RabbitMQ)
    常见面试题(Redis)
    某奥笔试题
    Servlet
    1——Django的基础及环境搭建
    6.13---example
    6.12---知道参数的重要性------插入数据-删除数据-修改数据注意Map
    6.12---前提两个对象的成员必须一致,才能将有数据的对象将数据传给反射获取的对象conver(有数据对象,目标对象)
  • 原文地址:https://www.cnblogs.com/fanling999/p/7817267.html
Copyright © 2020-2023  润新知