1 题目

2 思路与代码

  • 思路一:暴力法(两层For循环)

    • 时间复杂度:O(n^2)

      • 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间。因此时间复杂度为 O(n^2)。
    • 空间复杂度:O(1)
    • 原理:遍历每个元素 xx,并查找是否存在一个值与 target - x相等的目标元素
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target){
static int result[2]= {0};
for(int i=0;i<numsSize;i=i++){
for(int j=i+1;j<numsSize;j=j++){ //【trick】“int j=i+1;”而非“int j=0”
if(nums[i]+nums[j]==target){
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
  • 思路二:两遍哈希表

    • 时间复杂度:O(n)

      • 把包含有 n 个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1) ,所以时间复杂度为O(n)
    • 空间复杂度:O(n)
      • 所需的额外空间取决于哈希表中存储的元素数量,该表中存储了 n 个元素
class Solution {
/*
思路:两遍哈希表
推荐文献:
https://baijiahao.baidu.com/s?id=1628609734622761569&wfr=spider&for=pc
*/
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap();
for(int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
for(int j=0;j<nums.length;j++){
int tmp = target - nums[j];
if(map.containsKey(tmp) && map.get(tmp)!=j){
return new int [] { j, map.get(tmp) };
}
}
throw new IllegalArgumentException("No two sum solution!");
}
}
  • 思路三:一遍哈希表

    • 时间复杂度:O(n)

      • 只遍历了包含有n 个元素的列表一次。在表中进行的每次查找只花费 O(1) 的时间
    • 空间复杂度:O(n)
      • 所需的额外空间取决于哈希表中存储的元素数量,该表最多需要存储 n 个元素。
    • 原理:通过思路二,可以推得:上述过程可以一次完成。在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。
class Solution {//一次Hash查表
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap();
for(int i=0;i<nums.length;i++){
int tmp = target - nums[i];
if(map.containsKey(tmp) && map.get(tmp)!=i){
return new int [] { i, map.get(tmp) };
} else {
map.put(nums[i],i);
}
}
// for(int j=0;j<nums.length;j++){
// int tmp = target - nums[j];
// if(map.containsKey(tmp) && map.get(tmp)!=j){
// return new int [] { j, map.get(tmp) };
// }
// }
throw new IllegalArgumentException("No two sum solution!");
}
}

3 参考文献

4 博文遗留问题

  • (数据结构/Java中)HashMap/哈希表 查询的原理与实现?

最新文章

  1. SQL数据库中字段类型 与C#中的对应字段类型
  2. C语言习题(结构)
  3. C# NPOI 导入与导出Excel文档 兼容xlsx, xls
  4. Effeckt.css – CSS3 Transitions &amp; Animations 精妙应用
  5. JAVA实现多线程入门
  6. widowns 列出文件目录树结构 tree命令
  7. JS 之性能优化(2)
  8. android的R.java
  9. [转载]DIV CSS设计时IE6、IE7、FF 与兼容性有关的特性
  10. Linq学习之旅——LINQ查询表达式
  11. kafka相关应用
  12. C 运算符与表达式
  13. Java EE (4) -- Java EE 6 Java Persistence API Developer Certified Expert(1z0-898)
  14. Description has only two Sentences(欧拉定理 +快速幂+分解质因数)
  15. U盘分区后合并
  16. php |= 什么意思
  17. 内存管理-MRC与ARC详解
  18. Linux编程 11(shell全局环境变量与局变环境变量)
  19. h5py库安装问题解决
  20. 2017-2018-1 20155232 嵌入式C语言——时钟

热门文章

  1. ping加上时间信息
  2. 从c到c++&lt;一&gt;
  3. devops发展历程
  4. Java 基础 面向对象- 成员内部类/局部内部类/举例Comparable 接口的匿名内部类
  5. for循环使用后contains方法失去效果
  6. Java锁--Condition
  7. PHP mysqli_close() 函数
  8. Activiti服务类- ManagementService服务类
  9. @Async 异步注释 @EnableAsync
  10. luogu2034