CF 791(div2) E. Typical Party in Dorm(計數,子集DP)
阿新 • • 發佈:2022-05-26
1. 兩數之和
-
暴力解法
:通過兩個for迴圈逐步遍歷,判斷是否有符合條件的答案 - 1.初始有對資料進行判斷,比如數字比目標值大就不用判斷,直接跳過,其實是不行的,因為裡面有負數,最後相減也可以得出正確答案,這是最初版本。
class Solution { public int[] twoSum(int[] nums, int target) { int[] dp = new int[2]; for(int i = 0 ;i <nums.length;i++){ if(nums[i]>Math.abs(target)){ continue; }else{ for(int j = i+1;j<nums.length;j++){ if(target == nums[i]+nums[j]){ dp[0] = i; dp[1] = j; } } } } return dp; } }
- 2.之後發現有負數這種情況後,直接取消了判斷,但這樣會增加時間複雜度,沒有做好優化。
class Solution { public int[] twoSum(int[] nums, int target) { int[] dp = new int[2]; for(int i = 0 ;i <nums.length;i++){ for(int j = i+1;j<nums.length;j++){ if(target == nums[i]+nums[j]){ dp[0] = i; dp[1] = j; } } } return dp; } }
-
雜湊表法
:先將資料存入雜湊表中,再使用目標值依次減去陣列中的資料,再從雜湊表中找是否有符合條件的值,如果有,將下標傳給result陣列
,返回結果。
class Solution { // HashMap // N is the size of nums // Time Complexity: O(N) // Space COmplexity: O(N) public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; //定義hashMap HashMap<Integer,Integer> map = new HashMap<>(); for(int i=0;i < nums.length;i++){ //將所有資料存入hash表中 map.put(nums[i],i); } //使用目標值減去陣列中的值,查看錶中是否有符合條件的值就返回 for(int j=0;j < nums.length; j++){ int diff = target - nums[j]; if(map.containsKey(diff)&&map.get(diff)!=j){ result[0] = j; result[1] = map.get(diff); return result; } } return result; } }