https://leetcode.com/problems/two-sum/

Example:

  1. Given nums = [2, 7, 11, 15], target = 9,
  2.  
  3. Because nums[0] + nums[1] = 2 + 7 = 9,
  4. return [0, 1].

Java:

版本1,暴力搜索(减少了部分搜索),预计打败全世界30%的答案。

  1. public int[] twoSum(int[] nums, int target) {
  2. int size = nums.length;
  3. int size2 = size - 1;
  4. for (int i=0; i<size2; i++) {
  5. for (int j=i+1; j<size; j++) {
  6. if ((nums[i] + nums[j]) == target) {
  7. int[] pair = new int[2];
  8. pair[0] = i;
  9. pair[1] = j;
  10. return pair;
  11. }
  12. }
  13. }
  14. int[] pair = new int[2];
  15. return pair;
  16. }

版本2,,通过HashMap解决循环匹配问题,预计打败全世界50%

  1. HashMap<Integer, Integer> mm = new HashMap<Integer, Integer>();
  2. int size = nums.length;
  3. for (int i=0; i<size; i++) {
  4. mm.put(nums[i], i);
  5. }
  6. Integer tmp = 0;
  7. Integer v= 0;
  8. for (int i=0; i<size; i++) {
  9. tmp= target - nums[i];
  10. v = mm.get(tmp);
  11. if (v != null && v.intValue()!=i) {
  12. int[] pair = new int[2];
  13. pair[0] = i;
  14. pair[1] = v;
  15. return pair;
  16. }
  17. }
  18. int[] pair = new int[2];
  19. return pair;

版本3, 写到版本2的时候,肯定会想到把循环合并到一起执行,预计打败全世界58%。

  1. HashMap<Integer, Integer> mm = new HashMap<Integer, Integer>();
  2. int size = nums.length;
  3. Integer tmp = 0;
  4. Integer v= 0;
  5. mm.put(nums[0], 0);
  6.  
  7. for (int i=1; i<size; i++) {
  8. tmp= target - nums[i];
  9. v = mm.get(tmp);
  10. if (v != null) {
  11. int[] pair = new int[2];
  12. pair[0] = i;
  13. pair[1] = v;
  14. return pair;
  15. }
  16. mm.put(nums[i], i);
  17. }
  18.  
  19. int[] pair = new int[2];
  20. return pair;

版本4. 上面的代码已经不知道怎么优化,那么就减少int和Integer的转换吧,自己定制了一个IntHashMap,开始打败了68%,后面优化了hash的处理,提升到79%。

  1. static final int MISSIDX = -1;
  2. public int[] twoSum(int[] nums, int target) {
  3. IntHashMap mm = new IntHashMap();
  4. int size = nums.length;
  5. int tmp = 0;
  6. int v = 0;
  7. mm.put(nums[0], 0);
  8. for (int i = 1; i < size; i++) {
  9. tmp = target - nums[i];
  10. v = mm.get(tmp);
  11. if (v != MISSIDX) {
  12. int[] pair = new int[2];
  13. if (tmp == nums[i]) {
  14. pair[0] = v;
  15. pair[1] = i;
  16. } else {
  17. pair[0] = i;
  18. pair[1] = v;
  19. }
  20. return pair;
  21. }
  22. mm.put(nums[i], i);
  23. }
  24.  
  25. int[] pair = new int[2];
  26. return pair;
  27. }
  28.  
  29. static class IntHashMap {
  30. public static final int DEFAULT_INITIAL_CAPACITY = 16;
  31. public static final int MAXIMUM_CAPACITY = 1073741824;
  32. public static final float DEFAULT_LOAD_FACTOR = 0.75F;
  33. private transient IntEntry[] table;
  34. private transient int size;
  35. private int threshold;
  36. private final float loadFactor;
  37.  
  38. public IntHashMap(int initialCapacity) {
  39. this.loadFactor = 0.75F;
  40. int capacity = 1;
  41. while (capacity < initialCapacity) {
  42. capacity <<= 1;
  43. }
  44. this.threshold = ((int)(capacity * loadFactor));
  45. this.table = new IntEntry[capacity];
  46. }
  47.  
  48. public IntHashMap() {
  49. this.loadFactor = 0.75F;
  50. this.threshold = 12;
  51. this.table = new IntEntry[16];
  52. }
  53.  
  54. protected int indexFor(int key, int length) {
  55. return key & length - 1;
  56. }
  57.  
  58. public int get(int key) {
  59. int i = indexFor(key, this.table.length);
  60. IntEntry e = this.table[i];
  61. while (true) {
  62. if (e == null)
  63. return MISSIDX;
  64. if (e.key == key)
  65. return e.value;
  66. e = e.next;
  67. }
  68. }
  69.  
  70. public void put(int key, int value) {
  71. int i = indexFor(key, this.table.length);
  72. addEntry(key, value, i);
  73. }
  74.  
  75. private void addEntry(int key, int value, int bucketIndex) {
  76. IntEntry e = this.table[bucketIndex];
  77. this.table[bucketIndex] = new IntEntry(key, value, e);
  78. if (this.size++ >= this.threshold)
  79. resize(2 * this.table.length);
  80. }
  81.  
  82. protected void resize(int newCapacity) {
  83. IntEntry[] oldTable = this.table;
  84. int oldCapacity = oldTable.length;
  85. if (oldCapacity == 1073741824) {
  86. this.threshold = 2147483647;
  87. return;
  88. }
  89.  
  90. IntEntry[] newTable = new IntEntry[newCapacity];
  91. transfer(newTable);
  92. this.table = newTable;
  93. this.threshold = ((int) (newCapacity * this.loadFactor));
  94. }
  95.  
  96. private void transfer(IntEntry[] newTable) {
  97. IntEntry[] src = this.table;
  98. int newCapacity = newTable.length;
  99. for (int j = 0; j < src.length; j++) {
  100. IntEntry e = src[j];
  101. if (e != null) {
  102. src[j] = null;
  103. do {
  104. IntEntry next = e.next;
  105. int i = indexFor(e.key, newCapacity);
  106. e.next = newTable[i];
  107. newTable[i] = e;
  108. e = next;
  109. } while (e != null);
  110. }
  111. }
  112. }
  113.  
  114. public String toString() {
  115. return Arrays.deepToString(this.table);
  116. }
  117. }
  118.  
  119. static class IntEntry {
  120. protected final int key;
  121. protected int value;
  122. protected IntEntry next;
  123.  
  124. protected IntEntry(int k, int v, IntEntry n) {
  125. this.value = v;
  126. this.next = n;
  127. this.key = k;
  128. }
  129.  
  130. public int getKey() {
  131. return this.key;
  132. }
  133.  
  134. public int getValue() {
  135. return this.value;
  136. }
  137.  
  138. public void setValue(int newValue) {
  139. this.value = newValue;
  140. }
  141.  
  142. public boolean equals(Object o) {
  143. if (!(o instanceof IntEntry))
  144. return false;
  145. IntEntry e = (IntEntry) o;
  146. int eKey = e.getKey();
  147. int eVal = e.getValue();
  148. if (eKey == getKey()) {
  149. return eVal == MISSIDX ? false : getValue() == MISSIDX ? true
  150. : eVal == getValue();
  151. }
  152. return false;
  153. }
  154.  
  155. public int hashCode() {
  156. return this.key ^ (this.value == MISSIDX ? 0 : value);
  157. }
  158.  
  159. public String toString() {
  160. return "[" + key + "," + value + "]";
  161. }
  162. }

版本5. hashMap这个方向看来是尽头了,那用稀疏数组吧,貌似打败了87.62%

  1. static final int MISSIDX = -1;
  2. public int[] twoSum_0_4(int[] nums, int target) {
  3. SparseIntArray mm = new SparseIntArray();
  4. int size = nums.length;
  5. int tmp = 0;
  6. int v = 0;
  7. mm.put(nums[0], 0);
  8. for (int i = 1; i < size; i++) {
  9. tmp = target - nums[i];
  10. v = mm.get(tmp);
  11. if (v != MISSIDX) {
  12. int[] pair = new int[2];
  13. if (tmp == nums[i]) {
  14. pair[0] = v;
  15. pair[1] = i;
  16. } else {
  17. pair[0] = i;
  18. pair[1] = v;
  19. }
  20. return pair;
  21. }
  22. mm.put(nums[i], i);
  23. }
  24.  
  25. int[] pair = new int[2];
  26. return pair;
  27. }
  28.  
  29. static final int[] EMPTY_INTS = new int[0];
  30. static int idealByteArraySize(int need) {
  31. for (int i = 4; i < 32; i++)
  32. if (need <= (1 << i) - 12)
  33. return (1 << i) - 12;
  34.  
  35. return need;
  36. }
  37. static int idealIntArraySize(int need) {
  38. return idealByteArraySize(need * 4) / 4;
  39. }
  40. static int binarySearch(int[] array, int size, int value) {
  41. int lo = 0;
  42. int hi = size - 1;
  43.  
  44. while (lo <= hi) {
  45. final int mid = (lo + hi) >>> 1;
  46. final int midVal = array[mid];
  47.  
  48. if (midVal < value) {
  49. lo = mid + 1;
  50. } else if (midVal > value) {
  51. hi = mid - 1;
  52. } else {
  53. return mid; // value found
  54. }
  55. }
  56. return ~lo; // value not present
  57. }
  58. static class SparseIntArray {
  59. private int[] mKeys;
  60. private int[] mValues;
  61. private int mSize;
  62. public SparseIntArray() {
  63. this(10);
  64. }
  65. public SparseIntArray(int initialCapacity) {
  66. initialCapacity = idealIntArraySize(initialCapacity);
  67. mKeys = new int[initialCapacity];
  68. mValues = new int[initialCapacity];
  69. mSize = 0;
  70. }
  71. public int get(int key) {
  72. return get(key, MISSIDX);
  73. }
  74. public int get(int key, int valueIfKeyNotFound) {
  75. int i = binarySearch(mKeys, mSize, key);
  76.  
  77. if (i < 0) {
  78. return valueIfKeyNotFound;
  79. } else {
  80. return mValues[i];
  81. }
  82. }
  83. public void put(int key, int value) {
  84. int i = binarySearch(mKeys, mSize, key);
  85.  
  86. if (i >= 0) {
  87. mValues[i] = value;
  88. } else {
  89. i = ~i;
  90.  
  91. if (mSize >= mKeys.length) {
  92. int n = idealIntArraySize(mSize + 1);
  93.  
  94. int[] nkeys = new int[n];
  95. int[] nvalues = new int[n];
  96.  
  97. System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
  98. System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
  99.  
  100. mKeys = nkeys;
  101. mValues = nvalues;
  102. }
  103.  
  104. if (mSize - i != 0) {
  105. System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
  106. System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
  107. }
  108.  
  109. mKeys[i] = key;
  110. mValues[i] = value;
  111. mSize++;
  112. }
  113. }
  114.  
  115. public String toString() {
  116. if (mSize <= 0) {
  117. return "{}";
  118. }
  119.  
  120. StringBuilder buffer = new StringBuilder(mSize * 28);
  121. buffer.append('{');
  122. for (int i=0; i<mSize; i++) {
  123. if (i > 0) {
  124. buffer.append(", ");
  125. }
  126. int key = mKeys[i];
  127. buffer.append(key);
  128. buffer.append('=');
  129. int value = mValues[i];
  130. buffer.append(value);
  131. }
  132. buffer.append('}');
  133. return buffer.toString();
  134. }
  135. }

【leetcode】两数之和的更多相关文章

  1. 【数据结构】Hash表简介及leetcode两数之和python实现

    文章目录 Hash表简介 基本思想 建立步骤 问题 Hash表实现 Hash函数构造 冲突处理方法 leetcode两数之和python实现 题目描述 基于Hash思想的实现 Hash表简介 基本思想 ...

  2. LeetCode两数之和

    LeetCode 两数之和 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是 ...

  3. leetcode两数之和go语言

    两数之和(Go语言) 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复 ...

  4. leetcode 两数之和 python

      两数之和     给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 1 ...

  5. leetcode - 两数之和Ⅳ 输入BST(653)

    题目描述:给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true. 解题思路:根据二叉搜索树的特点,对二叉搜索树进行中序遍历可以得到一个从小到达排 ...

  6. Leetcode -- 两数之和Ⅰ

    1. 两数之和 题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 示例:给定 nums = [2, 7, 11, 15 ...

  7. leetcode 两数之和 II - 输入有序数组

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值 ...

  8. Leetcode 两数之和 (散列表)

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], target ...

  9. LeetCode两数之和-Python<一>

    下一篇:LeetCode链表相加-Python<二> 题目:https://leetcode-cn.com/problems/two-sum/description/ 给定一个整数数组和一 ...

  10. leetCode:twoSum 两数之和 【JAVA实现】

    LeetCode 两数之和 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标. 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素. 更多文章查看个人博客 个人博客地址:t ...

随机推荐

  1. PHP日期与时间

    时间戳是自 1970 年 1 月 1 日(00:00:00 GMT)以来的秒数.它也被称为 Unix 时间戳(Unix Timestamp).Unix时间戳(Unix timestamp),或称Uni ...

  2. Python爬虫Scrapy框架入门(2)

    本文是跟着大神博客,尝试从网站上爬一堆东西,一堆你懂得的东西 附上原创链接: http://www.cnblogs.com/qiyeboy/p/5428240.html 基本思路是,查看网页元素,填写 ...

  3. iOS APP提交上架最新流程(转)

    时隔1年又让我鼓捣iOS,刚接手就是上架,经验值为0的我,虽然内心是拒绝的,但还是要接受这项任务滴!也就是在被拒后重新审核,再改在提交...这样 反复的过程中也对上架流程熟悉了好多,写篇帖子送给同为菜 ...

  4. UWP 禁止Pivot swip 手势

    以前想要禁止内置的手势动作,看了一下网上是设置 IsLocked="True". 但是拿到UWP上来,靠,设置了之后header只显示当前的那个header.这样的设计真是丑爆了. ...

  5. 【tomcat ecplise】新下载一个tomcat,无法成功启动,或者启动了无法访问localhost:8080页面/ecplise无法添加新的tomcat/ecplise启动tomcat启动不起来

    今天转头使用ecplise,于是新下载一个tomcat7来作为服务器使用 但是问题来了: [问题1:全新的tomcat启动即消耗了不可思议的时间,并且启动了之前其他tomcat中的很多项目] [注意: ...

  6. 互联网+下PDA移动智能手持POS超市收银开单软件

    是一套专为中小超市.专卖店设计的收银管理软件,广泛应用于中小超市(百货商店).化妆品店.婴幼儿用品店.玩具店.保健品店.茶叶店. 电器.文具图书.手机通讯器材店等行业的中小型店面店铺.该系统具有完善的 ...

  7. 转-临界区对象TCriticalSection与TRTLCriticalSection的区别

    TRTLCriticalSection是一个结构体,在windows单元中定义: 是InitializeCriticalSection, EnterCriticalSection, LeaveCrit ...

  8. Android之UI编程(一):线性布局

    package com.example.fk_layout; import android.app.Activity; import android.os.Bundle; public class L ...

  9. C#-ASP.NET MVC-架构【1】-自定义错误页

    自定义异常本来是一件很简单的事情,没想到在做的过程中遇到各种坑,目前来说,还有Session过期和Ajax请求这两种情况没有特殊处理,其他的基本已经可以使用,等慢慢完善吧. 一.在web.config ...

  10. MD5 、 加密工具

    package com.cgcyiliao.server.util; import java.security.MessageDigest; import java.security.NoSuchAl ...