iT邦幫忙

2023 iThome 鐵人賽

DAY 21
0
自我挑戰組

30天leetcode學習旅程系列 第 21

項次 21 - backtracking-2

  • 分享至 

  • xImage
  •  

題目:39. Combination Sum

連結:https://leetcode.com/problems/combination-sum/description/

  • 等級:Medium
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
         List<List<Integer>> list = new ArrayList<>();
         Arrays.sort(candidates);
         backtrack(list, new ArrayList<>(),candidates,target,0);
         return list;
    }

    private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int target, int start)
    {
        if (target < 0) return;
        else if (target == 0) list.add(new ArrayList<>(tempList));
        else {
            for (int i = start; i < nums.length; i++) {
                tempList.add(nums[i]);
                backtrack(list, tempList,nums,target - nums[i],i);
                tempList.remove(tempList.size() - 1);
            }
        }
    }
  • Time complexity: O(n)
  • Space complexity: O(1)

題目:229. Majority Element II

連結:https://leetcode.com/problems/majority-element-ii/description/?envType=daily-question&envId=2023-10-05

  • 等級:Medium
class Solution {
    public List<Integer> majorityElement(int[] nums) {
        int count1 = 0, count2 = 0; 
        int candidate1 = 0, candidate2 = 0; 

        
        for (int i = 0; i < nums.length; i++) {
            
            if (count1 == 0 && nums[i] != candidate2) {
                count1 = 1;
                candidate1 = nums[i];
            } 
            
            else if (count2 == 0 && nums[i] != candidate1) {
                count2 = 1;
                candidate2 = nums[i];
            } 
            else if (candidate1 == nums[i]) {
                count1++;
            } else if (candidate2 == nums[i]) {
                count2++;
            } 
            else {
                count1--;
                count2--;
            }
        }

        List<Integer> result = new ArrayList<>();
        int threshold = nums.length / 3;

        count1 = 0;
        count2 = 0;
        for (int i = 0; i < nums.length; i++) {
            if (candidate1 == nums[i]) {
                count1++;
            } else if (candidate2 == nums[i]) {
                count2++;
            }
        }
        
        if (count1 > threshold) {
            result.add(candidate1);
        }
        if (count2 > threshold) {
            result.add(candidate2);
        }

        return result;
    }
}
  • Time complexity: O(n)
  • Space complexity: O(1)

上一篇
項次 20 - Breadth-First Search
下一篇
項次 22 - Heap
系列文
30天leetcode學習旅程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言