LeetCode解法从慢到快——1.Two Sum

  • Two Sum Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
    Example: Given nums = [2, 7, 11, 15], target = 9, 
    Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. 
    
  • Tips:
    1.可能会有两个相同的数字。
    2.注意有负数。

1.最容易想到的解法

  • 冒泡查询到目标数字,找出位数,返回即可。
    代码如下:
    public int[] twoSumOne(int[] nums, int target) {
      int[] result = new int[2];
      for (int i = 0; i < nums.length; i++) {
          for (int j = i + 1; j < nums.length; j++) {
              if (nums[i] + nums[j] == target) {
                  result[0] = i;
                  result[1] = j;
                  return result;
              }
          }
      }
      return null;
    }
    
    运行结果:
    Runtime: 39 ms
    Beats: 30.80%
    时间复杂度:O(n^2)
    空间复杂度:O(1)

2. 第二种进阶方法

  • 先快速排序数组,然后将i和i+1相加,取刚好大于target的两数,然后进行两个循环,小数和其后的所有数进行相加寻找target-小数,大数和其前的所有数进行相加寻找target-大数。
    public int[] twoSumTwo(int[] nums, int target) {
      int[] result = new int[2];
      ArrayList<Integer> numsSort = new ArrayList<>();
      for (int i = 0; i < nums.length; i++) {
          numsSort.add(nums[i]);
      }
      Arrays.sort(nums);
      int[] resultNum = new int[2];
      int small = -1;
      int large = -1;
      for (int i = 0; i < nums.length - 1; i++) {
          if (nums[i] + nums[i + 1] == target) {
              resultNum[0] = nums[i];
              resultNum[1] = nums[i + 1];
          } else if (nums[i] + nums[i + 1] > target) {
              small = i;
              large = i + 1;
          }
      }
      if (small != -1 || large != -1) {
          for (int i = 0; i < large; i++) {
              if (nums[i] + nums[large] == target) {
                  resultNum[0] = nums[i];
                  resultNum[1] = nums[large];
              }
          }
    
          for (int i = nums.length - 1; i > small; i--) {
              if (nums[i] + nums[small] == target) {
                  resultNum[0] = nums[small];
                  resultNum[1] = nums[i];
              }
          }
      }
    
      for (int i = 0; i < numsSort.size(); i++) {
          if (numsSort.get(i) == resultNum[0] && result[0] == 0) {
              result[0] = i;
          } else if (numsSort.get(i) == resultNum[1] && result[1] == 0) {
              result[1] = i;
          }
      }
      return result;
    }
    
    public int[] quickSort(int[] array, int begin, int end) {
      if (array == null || begin < end) {
          int p = patition(array, begin, end);
          quickSort(array, begin, p - 1);
          quickSort(array, p + 1, end);
      }
      return array;
    }
    
    private int patition(int[] array, int begin, int end) {
      int key = array[begin];
      while (begin < end) {
          while (begin < end && array[end] >= key) {
              end--;
          }
          array[begin] = array[end];
          while (begin < end && array[begin] < key) {
              begin++;
          }
          array[end] = array[begin];
      }
      array[begin] = key;
      return begin;
    }
    
    结果:出现了两个问题
    1. 使用快排后堆栈溢出。
    2. 当nums为负数的时候,无法得到其中转折处数字。

3. 使用哈希列表

  • 首先将所有元素和index放入hashmap中,然后循环数组,每次去找target-nums[i]是否在hashmap中。找到后返回i和hashmap中的index。
    public int[] twoSumThree(int[] nums, int target) {
      Map<Integer, Integer> map = new HashMap<>();
      for (int i = 0; i < nums.length; i++) {
          map.put(nums[i], i);
      }
      for (int i = 0; i < nums.length; i++) {
          int other = target - nums[i];
          if (map.containsKey(other) && map.get(other) != i) {
              return new int[]{i, map.get(other)};
          }
      }
      throw new IllegalArgumentException("No two sum solution");
    }
    
    Runtime:10 ms
    Beats:56.03%
    时间复杂度:O(n)
    空间复杂度:O(n)
    将此算法优化,将两个循环归为一个循环,并且不做i的判断。
    public int[] twoSumFour(int[] nums, int target) {
      Map<Integer, Integer> map = new HashMap<>();
      for (int i = 0; i < nums.length; i++) {
          if (map.containsKey(target - nums[i])) {
              return new int[]{i, map.get(target - nums[i])};
          }
          map.put(nums[i], i);
      }
      throw new IllegalArgumentException("No two sum solution");
    }
    
    Runtime:8 ms
    Beats:76.25%
    时间复杂度:O(n)
    空间复杂度:O(n)

4. 2方法的进阶优化

  • 使用arrays.sort方法进行快排,然后首位之和大于target则尾部index减1,小于target则首位index加1。这样找到和刚好与target相等的数字,循环后找到index数组。

    public int[] twoSumFive(int[] nums, int target) {
          int[] result = new int[2];
          int[] copyNum = new int[nums.length];
          for (int i = 0; i < copyNum.length; i++) {
              copyNum[i] = nums[i];
          }
          Arrays.sort(copyNum);
          int left = 0;
          int right = copyNum.length - 1;
          while (left < right) {
              int sum = copyNum[left] + copyNum[right];
              if (sum == target) {
                  break;
              } else if (sum > target) {
                  right--;
              } else {
                  left++;
              }
          }
          for (int i = 0; i < nums.length; i++) {
              if (nums[i] == copyNum[left]) {
                  result[0] = i;
              }
          }
          for (int i = nums.length - 1; i >= 0; i--) {
              if (nums[i] == copyNum[right]) {
                  result[1] = i;
              }
          }
          return result;
      }
    

    Runtime:6ms
    Beats:98.91%

    针对该方法再次进行优化
    首先复制数组使用Arrays.copyOf()
    将两次循环摘出来一个函数。

     public int[] twoSumSix(int[] nums, int target) {
          int[] sortNums = Arrays.copyOf(nums, nums.length);
          Arrays.sort(sortNums);
          int i = 0;
          int j = sortNums.length - 1;
    
          while (i < j) {
              if (sortNums[i] + sortNums[j] == target) {
                  return twoIndexes(sortNums[i], sortNums[j], nums);
              } else if (sortNums[i] + sortNums[j] > target) {
                  j--;
              } else {
                  i++;
              }
          }
          return new int[2];
    
      }
    
      public int[] twoIndexes(int num1, int num2, int[] nums) {
          int[] res = new int[2];
          int count = 0;
          for (int i = 0; i < nums.length; i++) {
              if (nums[i] == num1 || nums[i] == num2) {
                  res[count] = i;
                  count++;
              }
          }
          return res;
      }
    

    Runtime:5ms

5. 最快的方法

  • 投机取巧,首先,知道数列中最大的数字。20050
    知道数列中最大的负数。size=5。
    以最大的数字为下标去申请数组空间。
    public int[] twoSumEight(int[] nums, int target) {
      int[] map = new int[20050];
      int size = 5;
      for (int i = 0; i < nums.length; i++) {
          map[nums[i] + size] = (i + 1);
          int diff = target - nums[i + 1] + size;
          if (diff < 0) continue;
          int d = map[diff];
          if (d > 0)
              return new int[]{d - 1, i + 1};
      }
      return null;
    }
    
    Runtime:3ms

6.总结

  • 两数运算得一数时。
    1. 冒泡 初级并且低效。
    2. 哈希表。
    3. 排序后首尾缩小得到两数。
    4. 知道最大数,使用数组下标最快。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,653评论 0 33
  • [ 80 questions / 3 ~= 27 a month..ok.. ] 1.29: remove_dup...
    陈十十阅读 460评论 0 1
  • 从今天开始,写一下我在刷 LeetCode 时的心得体会,包括自己的思路和别人的优秀思路,欢迎各种监督啊! ...
    秋名山菜车手阅读 926评论 0 1
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,275评论 18 399
  • 今天在自习室无聊转笔,旁边一美女用一种很惊异的眼神看着我,结果我转得更起劲了。突然感觉有什么东西甩到脸上了,啊!哥...
    梓毓爸阅读 162评论 0 3