Leecode热题100---1:两数之和

题目:从nums中找出两个元素,它们的和等于target,返回下标。

C++:
1、直接暴力法

写嵌套循环,让每一个元素和其他元素分别相加,判断和是否等于target,等于就返回下标。

cpp 复制代码
#include <iostream>
#include <vector>

//int &nums:一个整型变量的引用
//vector<int> nums:nums是一个容器变量,容器名称为vector,容器内存的数据为int型
//vector<int> &nums:nums为一个引用,引用的内容是vector这个容器内部存放的整型数据

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		int i, j;
		for (i = 0; i<nums.size() - 1; i++)
		{
			for (j = i + 1; j<nums.size() - 1; j++)
			{
				if (nums[i] + nums[j] == target)
				{
					return{ i, j };
				}
			}
		}
		return{ };
	};
};

int main()
{
	int target = 8;
	Solution two;

	vector<int> arr = { 1, 2, 3, 4, 5, 6, 7 };

	cout << "[" << two.twoSum(arr, target)[0] << "," << two.twoSum(arr, target)[1] << "]" << endl;
	system("pause");
	return 0;
}

2、find函数

遍历nums的每一个元素,用find方法从剩下的元素中找匹配的加数,找到就返回下标。

cpp 复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 遍历nums
        for(int i=0; i<nums.size(); i++){
            // 寻找另一个数,it为迭代器
            auto it = find(nums.begin()+i+1, nums.end(), target-nums[i]);
            // 如果找到另一个数
            if(it != nums.end()){
                // 迭代器转化为下标
                int other = it-nums.begin();
                return {i, other};
            }
        }
        return {};
    }
};

3、使用unordered_map,即哈希表

遍历nums的每一个元素,从哈希表中找匹配的加数,找到则返回下标,找不到就存入哈希表。

cpp 复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 声明无序哈希容器
        unordered_map<int, int> hash;
        // 遍历nums
        for(int i=0; i<nums.size(); i++){
            // 在哈希表中寻找另一个数
            auto it = hash.find(target-nums[i]);
            // 如果找到另一个数
            if(it != hash.end()){
                return {i, it->second};
            }
            // 如果没找到,将当前遍历元素存入哈希表
            hash[nums[i]] = i;
        }
        return {};
    }
};

注:

1、vector的初始化方法,举例:vector nums{1, 2, 3}。

2、迭代器转下标的语法,举例:int index = it - nums.begin()。

3、向量的find方法的时间复杂度为O(n),哈希表的find方法的时间复杂度为O(1)。因为哈希表在查找的时候是通过内部的哈希函数进行计算的,不像向量的find是单纯地遍历元素。

python:
1、暴力解法

python 复制代码
class Solution:
    def twoSum(self,nums:List[int],target:int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    return [i,j]
        return []

2、排序+双指针

python 复制代码
# 思路:copy一个临时temp,排序后查找和为target的两数索引,根据索引取值并求得在原nums中的索引并返回
import cv2
import numpy as np
class Solution2:
    def twoSum(self,nums:List[int],target:int) -> List[int]:
        temp=nums.copy()
        temp.sort()
        i=0
        j=len(nums)-1
        while i<j:
            if(temp[i]+temp[j])>target:
                j=j-1
            elif(temp[i]+temp[j])<target:
                i=i+1
            else:
                break
        # index() 函数用于从列表中找出某个值第一个匹配项的索引位置。
        p=nums.index(temp[i])
        nums.pop(p)  # pop()用于删除并返回列表中的一个元素(默认为最后一个元素)
        k=nums.index(temp[j])
        
        if k>=p:
            k=k+1
        return [p,k]
相关推荐
闪电麦坤9521 分钟前
Leecode热题100:环形链表(链表)
数据结构·链表·leecode
天赐学c语言1 天前
1.18 - 滑动窗口最大值 && 子类的指针转换为父类的指针,指针的值是否会改变
数据结构·c++·算法·leecode
天赐学c语言2 天前
1.17 - 排序链表 && 虚函数指针是什么时候初始化的
数据结构·c++·算法·链表·leecode
闪电麦坤952 天前
Leecode热题100:合并区间(数组)
数据结构·算法·leecode
天赐学c语言3 天前
1.16 - 二叉树的中序遍历 && 动态多态的实现原理
数据结构·c++·算法·leecode
天赐学c语言5 天前
1.14 - 用栈实现队列 && 对模板的理解以及模板和虚函数区别
c++·算法·leecode
天赐学c语言12 天前
1.7 - 删除排序链表中的重要元素II && 哈希冲突常用解决冲突方法
数据结构·c++·链表·哈希算法·leecode
闪电麦坤9512 天前
多线程:按序打印问题(信号量)
c++·多线程·leecode
天赐学c语言13 天前
1.6 - 复制IP地址 && vector和list的区别
c++·算法·leecode
天赐学c语言14 天前
1.5 - 二叉树中的最大路径 && C++的类型转换
c++·算法·leecode