leetcode2023-07-15

转化时间需要的最少操作数

class Solution {
    public int convertTime(String current, String correct) {
        String[] split1 = current.split(":");
        int hour1 = Integer.valueOf(split1[0]);
        int mimute1 = Integer.valueOf(split1[1]);
        int time1 = 60 * hour1 + mimute1;

        String[] split2 = correct.split(":");
        int hour2 = Integer.valueOf(split2[0]);
        int mimute2 = Integer.valueOf(split2[1]);
        int time2 = 60 * hour2 + mimute2;

        int diff = time2 - time1;
        int ans = 0;
        while (diff > 0) {
            if (diff >= 60) {
                diff -= 60;
                ++ans;
            } else if (diff >= 15) {
                diff -= 15;
                ++ans;
            } else if (diff >= 5) {
                diff -= 5;
                ++ans;
            } else if (diff >= 1) {
                diff -= 1;
                ++ans;
            }
        }
        return ans;

    }
}

按奇偶性交换后的最大数字

class Solution {
    public int largestInteger(int num) {
        List<Integer> odds = new ArrayList<>();
        List<Integer> evens = new ArrayList<>();
        List<Integer> isOdd = new ArrayList<>();
        while (num > 0) {
            int temp = num % 10;
            num /= 10;
            if (temp % 2 == 0) {
                evens.add(temp);
                isOdd.add(0);
            } else {
                odds.add(temp);
                isOdd.add(1);
            }
        }
        Collections.sort(odds);
        Collections.sort(evens);
        int ans = 0;
        int i = odds.size() - 1;
        int j = evens.size() - 1;
        for (int k = isOdd.size() - 1; k >= 0; --k) {
            int isOd = isOdd.get(k);
            ans *= 10;
            if (isOd == 0) {
                ans += evens.get(j--);
            } else {
                ans += odds.get(i--);
            }
        }
        return ans;
    }
}

找到最接近 0 的数字

class Solution {
    public int findClosestNumber(int[] nums) {
        int ans = -100001;
        for (int num : nums) {
            if (Math.abs(ans) > Math.abs(num) ) {
                ans = num;
            } else if (Math.abs(ans) == Math.abs(num) ) {
                ans = Math.max(ans, num);
            }
        }
        return ans;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容