1. 程式人生 > >leetCode 之 K Sum()問題

leetCode 之 K Sum()問題

import java.util.*;
//Given nums = [2, 7, 11, 15], target = 9,
//Because nums[0] + nums[1] = 2 + 7 = 9,
//return [0, 1].
//思路:先建立一個int[2]陣列result存放返回值,然後遍歷,
//其中一個為cur=nums[i],另一個toFind=target-nums[i],//如果發現之前需要這個差值,那就找index。
//如果沒有,就put到map裡  //返回result,迴圈結束
public class Solution { public int[] twoSum(int[] nums, int target) { 
//建立一下陣列,要存兩個index的陣列。 
int[] result = new int[2]; //這裡用hashtable也行,看心情。 
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
//掃一遍陣列,一邊掃一邊存
 for(int i = 0; i < nums.length; i++)
{ int cur = nums[i]; //這裡搞出來個差值,其實差值是在沒找到之後新增到map裡面的。 
int toFind = target - cur; 
//如果發現之前需要這個差值,那就找index。
 if(map.containsKey(cur)){ result[0] = map.get(cur); result[1] = i; return result; } 
//如果沒有,就put到map裡面 
else{ map.put(toFind, i); 
} } 
return result;
 }}
如果遇到threeSum呢?fourSum?

【題目】

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

提示:

  • a<=b<=c
  • 避免結果集中有重複,因為陣列時排好序的,所以當一個數被放到結果集中的時候,其後面和它相等的直接被跳過。
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)
【思路】

K Sum問題是一個系列,部落格 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 和https://blog.csdn.net/ljiabin/article/details/40620579總結得比較完整,有興趣可以去看。

暴力解決法:三層for迴圈,但是時間複雜度是O(n^3),而且還要處理重複的問題,顯然不是題目想要的解法。

排序演算法:時間複雜度為O(nlgn),小於O(n^2),那麼我們不妨先對陣列排個序。

對於3Sum ,我們可以先固定一個數,然後找另外兩個數之和為第一個數的相反數就可以了。

【Java程式碼】O(n^2)

  1. public
    class Solution {  
  2.     List<List<Integer>> ret = new ArrayList<List<Integer>>();  
  3.     public List<List<Integer>> threeSum(int[] num) {  
  4.         if (num == null || num.length < 3return ret;  //如果陣列元素個數<3
  5.         Arrays.sort(num);  //呼叫Arrays的sort方法對num從小到大排序;
  6.         int len = num.length;  //用for迴圈遍歷,若兩個元素相等,則跳出,呼叫find(),尋找兩個數與num[i]的和為0;
  7.         for (int i = 0; i < len-2; i++) {  
  8.             if (i > 0 && num[i] == num[i-1]) continue;  
  9.             find(num, i+1, len-1, num[i]); //尋找兩個數與num[i]的和為0
  10.         }  
  11.         return ret;  
  12.     }  
  13.       //find方法,num[l] + num[r] + target == 0,則這三個值add到列表物件中
  14.     publicvoid find(int[] num, int begin, int end, int target) {  
  15.         int l = begin, r = end;  
  16.         while (l < r) {  
  17.             if (num[l] + num[r] + target == 0) {  
  18.                 List<Integer> ans = new ArrayList<Integer>();  
  19.                 ans.add(target);  
  20.                 ans.add(num[l]);  
  21.                 ans.add(num[r]);  
  22.                 ret.add(ans); //放入結果集中
  23.                 while (l < r && num[l] == num[l+1]) l++;  
  24.                 while (l < r && num[r] == num[r-1]) r--;  
  25.                 l++;  
  26.                 r--;  
  27.             } elseif (num[l] + num[r] + target < 0) {  
  28.                 l++;  
  29.             } else {  
  30.                 r--;  
  31.             }  
  32.         }  
  33.     }  
  34. }  

注意,對於 num[i],尋找另外兩個數時,只要從 i+1 開始找就可以了。

相關推薦

leetCode K Sum()問題

import java.util.*; //Given nums = [2, 7, 11, 15], target = 9, //Because nums[0] + nums[1] = 2 + 7 = 9, //return [0, 1]. //思路:先建立一個int[2]陣

leetcodeRange Sum Query

題目: 給定一個整數陣列  nums,求出陣列從索引 i 到 j  (i ≤ j) 範圍內元素的總和,包含 i,  j 兩點。 示例: 給定 nums = [-2, 0, 3, -5, 2, -1],求和函式為 sumRange() sumRange(0, 2) -&

LeetCode Two Sum(C)

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

javascript實現leetcodetwo 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

LeetCode Two Sum — C++ 實現

Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should re

leetCodeTwo Sum python實現

1. Two Sum 要求: Given an array of integers, return indices of the two numbers such that they add up to a specific target。 You ma

leetcode two sum (easy)c++

nbsp urn () lin for class result pre code 1.數組的長度 length() 2.容器vector長度 size() 3.容器vector vector是C++標準模板庫中的部分內容,它是一個多功能的,能夠操作多種數據結構和算

LeetCode 167. Two Sum II - Input array is sorted (兩數之和二 - 輸入的是有序數組)

point find leetcode algorithm 個數 tar div solution runtime Given an array of integers that is already sorted in ascending order, find two

LeetCode 560. Subarray Sum Equals K (子數組之和等於K

它的 ash tar spa logs his map 可能 解法 Given an array of integers and an integer k, you need to find the total number of continuous subarrays

LeetCode 560. Subarray Sum Equals K

題解 看到連續子序列和,必然想到字首和。但是光有字首和這題還做不了,如何使得和為目標數目呢? 此題和前面做過的一道4SUM有點像,關鍵還是用map來儲存便於查詢。 設想 map[ sum ] 表示字首和

leetcodeReverse Nodes in k-Group

題目: Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is les

leetcode陣列中的第K個最大元素

leetcode之陣列中的第K個最大元素 在未排序的陣列中找到第 k 個最大的元素。請注意,你需要找的是陣列排序後的第 k 個最大的元素,而不是第 k 個不同的元素。 示例 1: 輸入: [3,2,1,5,6,4] 和 k = 2 輸出: 5 示例 2: 輸入: [3,2,3

Crack LeetCode 1. Two Sum

https://leetcode.com/problems/two-sum/ 基本思路是做一個hanshmap,然後迭代查詢/插入這個hashmap。時間複雜度是O(n),空間複雜度也是O(n)。下文給出了C++和python的程式碼,python的程式碼非常簡潔,只有7行。 struct So

Crack LeetCode 23. Merge k Sorted Lists

本題有兩種解法,一是採用之前歸併排序裡面的merge函式把連結串列兩輛合併;二是採用堆演算法,具體參考這個連結: https://blog.csdn.net/linhuanmars/article/details/19899259 解法一的時間複雜度是O(n log(n)),空間複雜度是O(1);解

Crack LeetCode 124. Binary Tree Maximum Path Sum

https://leetcode.com/problems/binary-tree-maximum-path-sum/ 本題的難點在於每條路徑可以由樹中的任意兩個節點相連組成,解題方法還是遞迴。需要注意的是遞迴函式的返回值不是子樹的和,而是包含根節點的左子樹、根節點或者包含根節點的右子樹,這也是

leetcode刷題Two Sum(1)

給定一個整數陣列 nums 和一個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。 你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個陣列中同樣的元素。 示例: 給定 nums = [2, 7, 11, 15], target = 9 因為 nums

leetcodeMerge k Sorted Lists

題目: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [   1->

leetcode問題一:Two Sum

1. 問題描述 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 i

leetcode 363. Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no la

LeetCode347. 前K個高頻元素

參考知識:優先佇列      (通過最大堆實現的) 優先佇列的作用是能保證每次取出的元素都是佇列中權值最小的(Java的優先佇列每次取最小元素)。這裡牽涉到了大小關係,元素大小的評判可以通過元素本身的自然順序(natural ordering