鱼C论坛

 找回密码
 立即注册
查看: 1685|回复: 1

[已解决]c++l 哈希表实现两数之和 很短

[复制链接]
发表于 2021-9-26 22:04:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
为什么程序输出一直是0,0,无法进入if判断,leecode 里面同样的逻辑是可以运行的

  1. #include<stdio.h>
  2. #include <time.h>
  3. #include <cstdlib>
  4. #include <string.h>
  5. #include<vector>
  6. #include<string>
  7. #include<map>
  8. #include<algorithm>
  9. //给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。
  10. //你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
  11. //你可以按任意顺序返回答案。
  12. //复杂度小于O(n^2)

  13. //c++哈希表


  14. using namespace std;
  15. #include <unordered_map>
  16. #include <unordered_set>
  17. int main()
  18. {
  19.         int nums[] = { 3, 2, 4 };
  20.         int size_of;
  21.         int a = 1, b = 1, target = 6;
  22.         size_of = sizeof(nums) / 4;

  23.         map<int, int> mp;
  24.         int i;
  25.         for (i = 0; i < size_of; i++)
  26.         {
  27.                 if (mp.count(target - nums[i]) >0)
  28.                 {
  29.                         a = i;
  30.                         b = mp[target - nums[i]];
  31.                 }
  32.         }

  33.         printf("%d  %d", a, b);
  34.         return 0;
  35. }
复制代码
最佳答案
2021-9-26 23:54:14
三十五行之后加一行在循环里if外,应该就可以了
  1. mp[nums[i]] = i;
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-9-26 23:54:14 | 显示全部楼层    本楼为最佳答案   
三十五行之后加一行在循环里if外,应该就可以了
  1. mp[nums[i]] = i;
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-16 08:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表