• 1. Two Sum


    1. Two Sum

    题目

    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].
    
    

    解析

    class Solution_1 {
    public:
    	// O(n^2)
    	vector<int> twoSum(vector<int> &numbers, int target) {
    
    		vector<int> vec;
    		if (numbers.size()==0)
    		{
    			return vec;
    		}
    
    		for (int i = 0; i < numbers.size()-1;i++)
    		{
    			for (int j = i + 1; j < numbers.size();j++)
    			{
    				if (numbers[i]+numbers[j]==target)
    				{
    					vec.push_back(i);
    					vec.push_back(j);
    					break;
    				}
    			}
    		}
    
    		return vec;
    	}
    
    	// 使用一个哈希表(unorder_map)来解,第一遍扫描,保存到哈希表中,第二遍扫,看target-n在不在哈希表中,时间复杂度为O(n)。
            // 元素有重复的时候multi??
    	vector<int> twoSum(vector<int> a, int target) {
    		int i, j, k, l, m, n;
    		map<int, int>mymap;
    		map<int, int>::iterator it;
    		vector<int>ans;
    		for (i = 0; i < a.size(); i++){
    			it = mymap.find(target - a[i]);
    			if (it != mymap.end()){
    				ans.push_back(it->second);
    				ans.push_back(i);
    				return ans;
    			}
    			else{
    				mymap.insert(make_pair(a[i], i));
    			}
    		}
    	}
    
    	vector<int> twoSum1(vector<int>& nums, int target) {
    		vector<int> vec;
    		if (nums.size()==0)
    		{
    			return vec;
    		}
    		sort(nums.begin(), nums.end()); 
    		int start = 0, end = nums.size()-1;
    		while (start<end)
    		{
    			if (nums[start]+nums[end]==target)
    			{
    				vec.push_back(start);
    				vec.push_back(end);
    				break;
    			}
    			else if (nums[start] + nums[end] < target)
    			{
    				start++;
    			}
    			else
    			{
    				end--;
    			}
    		}
    		return vec; //返回值的排序后的index,不符合题意
    	}
    };
    

    题目来源

  • 相关阅读:
    C++11中右值引用和移动语义
    面试题3:自己实现单链表
    C++中指针和引用、数组之间的区别
    C++中对象模型
    C++中虚函数的动态绑定和多态性
    C++11中多线程库
    C++中友元
    C++中迭代器原理、失效和简单实现
    C++11中智能指针的原理、使用、实现
    C++中模板与泛型编程
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8276026.html
Copyright © 2020-2023  润新知