Leetcode 简单

Leetcode

  • [504. 七进制数](https://leetcode-cn.com/problems/base-7/)
  • [521. 最长特殊序列 Ⅰ](https://leetcode-cn.com/problems/longest-uncommon-subsequence-i/)
  • [258. 各位相加](https://leetcode-cn.com/problems/add-digits/)
  • [★2016. 增量元素之间的最大差值](https://leetcode-cn.com/problems/maximum-difference-between-increasing-elements/)
  • [2016. 增量元素之间的最大差值](https://leetcode-cn.com/problems/maximum-difference-between-increasing-elements/)
  • [★917. 仅仅反转字母](https://leetcode-cn.com/problems/reverse-only-letters/)
  • [717. 1比特与2比特字符](https://leetcode-cn.com/problems/1-bit-and-2-bit-characters/)
  • [1791. 找出星型图的中心节点](https://leetcode-cn.com/problems/find-center-of-star-graph/)
  • [1380. 矩阵中的幸运数](https://leetcode-cn.com/problems/lucky-numbers-in-a-matrix/)
  • [1342. 将数字变成 0 的操作次数](https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero/)
  • [1763. 最长的美好子字符串](https://leetcode-cn.com/problems/longest-nice-substring/)
  • [2047. 句子中的有效单词数](https://leetcode-cn.com/problems/number-of-valid-words-in-a-sentence/)
  • [2000. 反转单词前缀](https://leetcode-cn.com/problems/reverse-prefix-of-word/)
  • [2006. 差的绝对值为 K 的数对数目](https://leetcode-cn.com/problems/count-number-of-pairs-with-absolute-difference-k/)
  • [1189. “气球” 的最大数量](https://leetcode-cn.com/problems/maximum-number-of-balloons/)
  • [1725. 可以形成最大正方形的矩形数目](https://leetcode-cn.com/problems/number-of-rectangles-that-can-form-the-largest-square/)
  • [1984. 学生分数的最小差值](https://leetcode-cn.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/)
  • [1748. 唯一元素的和](https://leetcode-cn.com/problems/sum-of-unique-elements/)

504. 七进制数

class Solution:
    def convertToBase7(self, num: int) -> str:
        if num == 0: return "0"
        negative = num < 0
        num = abs(num)
        digits = []
        while num:
            num, r = divmod(num, 7)
            digits.append(str(r))
       
        if negative: digits.append('-')
        return ''.join(reversed(digits))

521. 最长特殊序列 Ⅰ

class Solution:
    def findLUSlength(self, a: str, b: str) -> int:
        m, n = len(a), len(b)
        if m != n: return max(m, n)
        else: return -1 if a == b else m

258. 各位相加

class Solution:
    def addDigits(self, num: int) -> int:       
        while num > 9: # 个位数字
            rem = 0 # 记各位的和
            while num:
                rem += num % 10
                num //= 10
            num = rem
        return num
class Solution {
    public int addDigits(int num) {
        while (num > 9){
            int rem = 0;
            while (num != 0){
                rem += num % 10;
                num /= 10;
            }
            num = rem;
        }
        return num;
    }
}

★2016. 增量元素之间的最大差值

class Solution:
    def maximumDifference(self, nums: List[int]) -> int:
        # res, n = -1, len(nums)
        # for i in range(n):
        #     for j in range(i+1, n):
        #         if nums[i] < nums[j]:                    
        #             res = max(res, nums[j]-nums[i])
		
		# ★维护一个最小值,从第二个开始,每个元素和最小值比较。 
        min_, res = nums[0], -1
        for x in nums[1:]:
            res = max(res, x - min_)
            min_ = min(min_, x)

        return res or -1
		
		# 加条件会变慢 if nums[j] > nums[i]
        # return max(0, max(nums[j] - nums[i] for i in range(len(nums)) for j in range(i+1, len(nums)))) or -1
class Solution {
    public int maximumDifference(int[] nums) {
        int res = -1, min = nums[0];
        // for (int i = 1; i < nums.length; i++){
        //     int tmp = nums[i] - min; 
        //     res = (tmp > res) ? tmp : res;
        //     min = (nums[i] < min) ? nums[i] : min;
        // }
        for (int i : nums){            
            res = Math.max(res, i - min);
            min = Math.min(i, min);
        }
        return (res == 0) ? -1:res; // 可能有相同元素存在
    }
}

2016. 增量元素之间的最大差值

class Solution:
    def maximumDifference(self, nums: List[int]) -> int:
        res, a = -1, nums[0]
        for b in nums[1:]:
            if a < b: res = max(res, b - a)
            else: a = min(a, b)                
        return res
class Solution {
    public int maximumDifference(int[] nums) {
        int res = -1, min = nums[0];
        for (int i : nums){            
            res = Math.max(res, i - min);
            min = Math.min(i, min);
        }
        return (res == 0) ? -1:res; // 可能有相同元素存在
    }
}

★917. 仅仅反转字母

class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        # x, i, j = list(s), 0, len(s)-1
        # while i < j:
        #     if not x[i].isalpha(): i += 1
        #     elif not x[j].isalpha(): j -= 1
        #     else: 
        #         x[i], x[j] = x[j], x[i]
        #         i += 1
        #         j -= 1
                
        # return "".join(x)    

        t, x = [c for c in s if c.isalpha()], []       
        for c in s:
            # if c.isalpha(): x.append(t.pop())
            # else: x.append(c)
            x.append(t.pop() if c.isalpha() else c)
        return "".join(x)

        # return ''.join(t.pop if c.isalpha() else c for c in s) 
class Solution {
    public String reverseOnlyLetters(String s) {
        int i = 0, j = s.length() - 1;
        char[] t = s.toCharArray();
        while (i < j){        
            if (!Character.isLetter(t[i])) i++;
            else if (!Character.isLetter(t[j])) j--; 
            else {
                char tmp =t[i]; t[i] = t[j]; t[j] = tmp; 
                i++; j--;            
            }
        }
        return new String(t);
        
        // StringBuilder sb = new StringBuilder();
        // char[] t = s.toCharArray();
        // int j = s.length() - 1;
        // for (char c : t){
        //     while (j > 0 && !Character.isLetter(t[j])) j--;
        //     sb.append(Character.isLetter(c) ? t[j--] : c);
        // }
        // return sb.toString();
    }
}

717. 1比特与2比特字符

遍历,遇到 0 走一步,遇到 1 走两步。

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        # n = len(bits)
        # i = n - 2
        # while i >= 0 and bits[i]: i -= 1
        # return (n - i) % 2 == 0
        
        i, n = 0, len(bits)
        while i < n - 1: i += bits[i] + 1
        return i == n - 1

1791. 找出星型图的中心节点

		# python
        return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]
        // java
        return (edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1]) ? edges[0][0] : edges[0][1];
    }
}

1380. 矩阵中的幸运数

class Solution:
    def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
        n = len(matrix[0])
        row, col = [0] * n, [0] * n # row[idx]行的最小值在 idx 列,col 列的最大值。
        for r in matrix:
            tmp, idx = inf, 0 # tmp 为当前行的最小值,对应的列为 idx。
            for j, v in enumerate(r):
                if v < tmp:
                    tmp = v
                    idx = j
                col[j] = max(col[j], v)
            row[idx] = max(row[idx], tmp) # 但保留最大值。
        return [row[i] for i in range(n) if row[i] == col[i]] 
        
        # row = [min(row) for row in matrix]
        # col = [max(col) for col in zip(*matrix)]
        # return [x for i, r in enumerate(matrix) for j, x in enumerate(r) if row[i] == col[j]] 

1342. 将数字变成 0 的操作次数

class Solution:
    def numberOfSteps(self, num: int) -> int:
        n = 0
        while num:
            num = num - 1 if num % 2 else num // 2
            n += 1
        return n
class Solution {
    public int numberOfSteps(int num) {
        int res = 0;
        while (num > 0) {
            if (num % 2 == 0) num >>= 1;
            else num--;
            res++;
        }
        return res;
    }
}

1763. 最长的美好子字符串

class Solution:
    def longestNiceSubstring(self, s: str) -> str:
        # n = len(s)
        # maxPos = maxLen = 0
        # for i in range(n):
        #     upp = low = 0
        #     for j in range(i, n):
        #         if s[j].islower(): low |= 1 << (ord(s[j]) - ord('a'))
        #         else: upp |= 1 << (ord(s[j]) - ord('A'))
        #         if upp == low and j - i + 1 > maxLen:
        #             maxPos, maxLen = i, j - i + 1
        
        # return s[maxPos: maxPos + maxLen]

        def f(s):
            w = set(s)   
            for c in w:
                if c.swapcase() not in w: break
            else: 
                res.append(s)    
                return
            for t in s.split(c):        
                if t: f(t) 
            
        res = ['']
        f(s)
        res.sort(key=lambda x : -len(x))
        return res[0]
        
        def f(s):
            # global x # Leetcode 不通过
            nonlocal x # Jupyterlab 不通过            
            w = set(s)   
            for c in w:
                if c.swapcase() not in w: break;                    
            else:   
                if len(s) > len(x): 
                    x = s
                    return
            for t in s.split(c): 
                if t: f(t)
                
        x = ''
        f(s)        
        return x
class Solution {
    public String longestNiceSubstring(String s) {
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++){
            int lower = 0, upper = 0;
            for (int j = i; j < s.length(); j++){
                char c = s.charAt(j);
                if (c > 96) lower |= 1 << c - 'a';
                if (c < 96) upper |= 1 << c - 'A';
                if (lower == upper && j + 1 - i > end - start){
                    start = i;
                    end = j + 1;
                }
            }
        }
        return s.substring(start, end);
    }
}

2047. 句子中的有效单词数

class Solution:
    def countValidWords(self, sentence: str) -> int:
        # res = 0
        # words = sentence.split()
        # for word in words:
        #     if word in ['!', '.', ',']: 
        #         res += 1
        #         continue
        #     if word[-1] in '!.,':
        #         word = word[:-1]
        #     if word[0] != '-' and word[-1] != '-':
        #         w = word.split('-')
        #         if len(w) <= 2 and all(x.isalpha() for x in w):
        #             res += 1
        # return res

        #regex = r'[a-z]*([a-z]-[a-z]+)?[!.,]?$'     
        regex = r"^([,.!]|[a-z]+(-[a-z]+)?[,.!]?)$"
        return sum(bool(re.match(regex, word)) for word in sentence.split())
class Solution {
    public int countValidWords(String sentence) {
        int res = 0;
        // String regex = "^([,.!]|[a-z]+(-[a-z]+)?[,.!]?)$";
        for (String s : sentence.split(" +"))           {
            // if (s.matches(regex)) res++;
            if (check(s)) res++;
        }
        return res;
    }

    public boolean check(String word) {
        if (word == "") return false;
        int n = word.length();
        boolean hyphen = false;
        for (int i = 0; i < n; i++) {
            if (Character.isDigit(word.charAt(i))) {
                return false;
            } else if (word.charAt(i) == '-') {
                if (hyphen == true || i == 0 || i == n - 1 || !Character.isLetter(word.charAt(i - 1)) || !Character.isLetter(word.charAt(i + 1))) {
                    return false;
                }
                hyphen = true;
            } else if ((word.charAt(i) == '!' || word.charAt(i) == '.' || word.charAt(i) == ',') && (i != n - 1)) {
                    return false;
            }
        }
        return true;
    }
}

2000. 反转单词前缀

class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        idx = word.find(ch) + 1
        return word[:idx][::-1] + word[idx:] if idx != 0 else word
class Solution {
    public String reversePrefix(String word, char ch) {        
        char[] arr = word.toCharArray();
        for (int i = 0, j = word.indexOf(ch); i < j; i++, j--){
            char tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
        return new String(arr);   
    }
}

2006. 差的绝对值为 K 的数对数目

class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        # 方法一:
        # res, n = 0, len(nums)        
        # for i in range(n):
        #     for j in range(i+1, n):
        #         if abs(nums[i]-nums[j]) == k:
        #             res += 1
        # return res

        # 方法二:哈希表
        # res, d = 0, defaultdict(int)
        # for i in nums:
        #     d[k+i] += 1
        # # for i in nums:          
        # #     res += d[i]
        # return sum(d[i] for i in nums)
        
        # 方法三:Counter
        # res, c = 0, Counter()
        # for i in nums:
        #     res += c[i + k] + c[i - k]
        #     c[i] += 1
        # return res
        c = Counter(nums)
        return sum(c[i + k] for i in nums)
class Solution {
    public int countKDifference(int[] nums, int k) {
        int[] c = new int[200];
        int ans = 0;
        for (int num : nums){
            ans += c[num + k] + (num >= k ? c[num - k] : 0);
            c[num]++;                     
            // c[num + k]++; 
            // if (num >= k) c[num - k]++;
            // ans += c[num];
        } 
        return ans;
    }
}

1189. “气球” 的最大数量

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;
        // return Arrays.stream(cnt).min().getAsInt();
        int ans = cnt[0];
        for (int i = 0; i < 5; i++) ans = Math.min(ans, cnt[i]);
        return ans; 
    }
}

1725. 可以形成最大正方形的矩形数目

class Solution:
    def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
        res = maxLen = 0
        for h, w in rectangles:
            minLen = min(h, w)
            if maxLen == minLen: res += 1
            elif maxLen < minLen:
                maxLen = minLen
                res = 1                
        return res
class Solution {
    public int countGoodRectangles(int[][] rectangles) {
        int res = 0, max = 0;
        for (int[] rec : rectangles){
            int min = Math.min(rec[0], rec[1]);
            if (max == min) res++;
            else if (max < min){
                max = min;
                res = 1;
            }
        }
        return res;
    }
}

1984. 学生分数的最小差值

class Solution:
    def minimumDifference(self, nums: List[int], k: int) -> int:
    	# 排序 滑动窗口 
        nums.sort()
        res = inf
        for i in range(len(nums) - k + 1):
            res = min(res, nums[i + k - 1]-nums[i])
            
        return res
class Solution {
    public int minimumDifference(int[] nums, int k) {
        Arrays.sort(nums);
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length - k + 1; i++){
            int tmp = nums[i+k-1] - nums[i];
            res = (tmp < res) ? tmp:res;
        }
        return res;
    }
}

1748. 唯一元素的和

class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        res = {}
        for i in nums:
            res[i] = res.get(i, 0) + 1
        
        return sum(x for x in res if res[x] == 1)

        res, ans = {}, 0
        for i in nums:
            if i in res:
                if res[i] == 1: ans -= i
                res[i] = 2
            else:
                res[i] = 1
                ans += i        
        return ans
class Solution {
    public int sumOfUnique(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int res = 0;

        // for (int num : nums){
        //     map.put(num, map.getOrDefault(num, 0) + 1);
        // }
        // for (Map.Entry entry : map.entrySet()) {
        //     if (entry.getValue() == 1) res += entry.getKey();
        // }        

        for (int num : nums) {
            if (!map.containsKey(num)) {
                res += num; // 先加上  
                map.put(num, 1);
            } else if (map.get(num) == 1) {
                res -= num; // 多个减一次
                map.put(num, 2);
            }
        }
        return res;
    }
}

class Solution {
    public int sumOfUnique(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length, ans = 0, start = 0;
        for (int i = 1; i < n; i++) {
            if (nums[start] != nums[i]){
                if (i - start == 1) ans += nums[start];
                start = i;
            }
        }
        if (n - start == 1) ans += nums[n - 1];
        return ans;
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)