Java算法 leetcode简单刷题记录9

Java算法 leetcode简单刷题记录9

  1. 购买俩块巧克力: https://leetcode.cn/problems/buy-two-chocolates/
    给定数组量并不大,因此也可以不用PriorityQueue,每次输出最小值;可以暴力循环
class Solution {
    public int buyChoco(int[] prices, int money) {
        int sum = Integer.MAX_VALUE;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                sum = Math.min(prices[i] + prices[j], sum);
            }
        }
        if (money >= sum) {
            return money - sum;
        }
        return money;
    }
}
  1. 移除字符中的尾随零: https://leetcode.cn/problems/remove-trailing-zeros-from-a-string/

  2. 最小化字符串长度: https://leetcode.cn/problems/minimize-string-length/
    有点陷入了误区,写了一会才发现可以更简单的…

class Solution {
    public int minimizedStringLength(String s) {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            set.add(String.valueOf(s.charAt(i)));
        }
        return set.size();
    }
}
  1. 半有序排列: https://leetcode.cn/problems/semi-ordered-permutation/
    按照题意写就行;
class Solution {
    public int semiOrderedPermutation(int[] nums) {
        if (nums[0] == 1 && nums[nums.length - 1] == nums.length) {
            return 0;
        }
        int max = -1;
        int min = 0;
        if (nums[0] != 1) {
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == 1) {
                    min = i;
                    break;
                } else if (nums[i] == nums.length) {
                    max = i;
                }
            }
        }
        if (nums[nums.length - 1] != 1) {
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == nums.length) {
                    max = i;
                    break;
                }
            }
        }
        // System.out.println(min + " " + max);
        if (max > min) {
            return min + (nums.length - 1 - max);
        }
        return min + (nums.length - 1 - max - 1);
    }
}
  1. 判断一个数是否迷人: https://leetcode.cn/problems/check-if-the-number-is-fascinating/
    按照题意直接写就行;

你可能感兴趣的:(JAVA,算法,算法,java,leetcode)