current position:Home>Java lesson 29 136 The number 1189 appears only once Maximum number of balloons

Java lesson 29 136 The number 1189 appears only once Maximum number of balloons

2022-04-29 06:11:19Yake1965

136. A number that appears only once

Leetcode
Knowledge point : map, HashMap, put, get, keySet, Map.Entry, entrySet

class Solution {
    
    public int singleNumber(int[] nums) {
    
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer i : nums) {
    
            map.put(i, map.get(i) == null ? 1 : map.get(i) + 1);
        }
        // for (Integer i: map.keySet()) if (map.get(i) == 1) return i; 

        for (Map.Entry<Integer, Integer> m : map.entrySet()) if (m.getValue() == 1) return m.getKey();
        return -1; // can't find it.

    	//  Method 2 : An operation 
        int res = 0;
        for (Integer i : nums) res ^= i;        
        return res;
    }
}

1189. “ balloon ” Maximum number of

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        # d = {c: 0 for c in 'balon'}
        # for c in text:
        # if c in 'balon':
        # d[c] += 1

        # return min(d[c]//2 if c in 'ol' else d[c] for c in d)
        
        c = Counter(x for x in text if x in  'balon')
        c['l'] //= 2
        c['o'] //= 2
        return min(c.values()) if len(c) == 5 else 0
class Solution {
    
    public int maxNumberOfBalloons(String text) {
    
        int[] cnt = new int[5];
        for (char ch : text.toCharArray()){
    
            if (ch == 'a') cnt[0]++;
            if (ch == 'b') cnt[1]++;
            if (ch == 'l') cnt[2]++;
            if (ch == 'o') cnt[3]++;
            if (ch == 'n') cnt[4]++;
        }   

        // for(int i = 0; i < text.length(); i++) {
    
        // switch(text.charAt(i)){
    
        // case 'a': cnt[0]++; break;
        // case 'b': cnt[1]++; break;
        // case 'l': cnt[2]++; break;
        // case 'o': cnt[3]++; break;
        // case 'n': cnt[4]++; //break;
        // // default: continue;
        // }
        // } 

        cnt[2] /= 2;
        cnt[3] /= 2;
        int ans = cnt[0];
        for (int i = 0; i < 5; i++) ans = Math.min(ans, cnt[i]);
        return ans; 
    }
}

class Solution {
    
    public int maxNumberOfBalloons(String text) {
    
        Map<Character, Integer> map = new HashMap<>();         
        for (char c : text.toCharArray()) {
    
            map.put(c, map.getOrDefault(c, 0) + 1);
        } 
        map.put('o', map.getOrDefault('o', 0)/2);
        map.put('l', map.getOrDefault('l', 0)/2);        
        int ans = map.getOrDefault('a', 0);
        for (char c : "balon".toCharArray())
            ans = Math.min(ans, map.getOrDefault(c, 0));
        return ans; 
    }
}

copyright notice
author[Yake1965],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/116/202204261000558787.html

Random recommended