力扣算法-1

打印 上一主题 下一主题

主题 939|帖子 939|积分 2817

力扣算法

1 两数之和

给定一个整数数组nums和一个整数目的值target,请你在数组中找出和为目的值target的那两个整数,返回他们的数组下标。
(1)暴力罗列

(罗列数组每一个数x,再寻找数组中是否存在 target -x)
  1. public int[] twoSum(int[] nums,int target) {
  2.         int n = nums.length;
  3.         for (int i = 0; i<n; ++i) {
  4.                 for(int j = i + 1; j < n;++j) {
  5.                         if (nums[i] + nums[j] == target) {
  6.                                 return new int[]{i,j};
  7.                         }
  8.                 }
  9.         }
  10. return new int[0];
  11. }
复制代码
(2)哈希表

对于每个x,我们查询哈希表中是否存在target-x,将x插入哈希表中
  1. public int[] twoSum(int[] nums,int target) {
  2.         Map<Integer,Integer> hashTable = new HashMap();
  3.         for(int i = 0;i<nums.length;++i) {
  4.                 if(hashTable.containsKey(target-nums[i])){
  5.                         return new int[] {hashTable.get(target-nums[i]),i};    //返回当前x的数组索引和哈希表中匹配的数组索引值
  6.                 }       
  7.                         hashTable.put(nums[i],i);
  8.         }
  9.         return new in[0];
  10. }
复制代码
2 无重复字符的最长子串

3 二叉树的前序遍历

[code][/code]
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

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

本版积分规则

八卦阵

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表