LeetCode

简介: LeetCode

2. 两数相加

  public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ln = new ListNode();
        ListNode p1 = l1, p2 = l2, p = ln;
        // 标志上一位如果超过10,下一位进1,即加一
        int flag = 0;
        while (p1 != null || p2 != null) {
            // p1,p2指向null 则值为0
            int num1 = p1 == null ? 0 : p1.val;
            int num2 = p2 == null ? 0 : p2.val;
            int res = num1 + num2 + (flag == 1 ? 1 : 0);
            p.val = res % 10;
            flag = 0;
            if (res > 9) flag = 1;
            // p1,p2 指向下一个节点,直到指向null为止.
            p1 = p1 == null ? p1 : p1.next;
            p2 = p2 == null ? p2 : p2.next;
            if (p1 == null && p2 == null) {
                // 结束最后一位, 也需进一,
                if (flag == 1) {
                    p = p.next = new ListNode();
                    p.val = 1;
                }
                p.next = null;
            } else
                p = p.next = new ListNode();
        }
        return ln;
    }

3. 无重复字符的最长子串

  public static int lengthOfLongestSubstring(String s) {
        int max = 0;
        char[] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            for (int j = i; j < s.length(); j++) {
                // 存在跳出, 不存在加入
                if(sb.indexOf(chars[j] + "") != -1) break;
                else sb.append(chars[j]);
                if (sb.length() > max) max = sb.length();
            }
            //重置字符串sb
            sb.setLength(0); 
        }
        return max;
    }

7. 整数反转

/**
 * @Author Tiam
 * @Date 2022/6/28 13:13
 * @Description: 7. 整数反转  victory
 */
public class Demo06 {
    public static void main(String[] args) {
        System.out.println(reverse(2432));
    }

    public static int reverse(int x) {
        long n = x % 10;
        while ((x /= 10) != 0) {
            n = n * 10 + x % 10;
        }
        if (n > Integer.MAX_VALUE || n < Integer.MIN_VALUE) return 0;
        return (int)n;
    }
}

8. 字符串转换整数 (atoi)

/**
 * @Author Tiam
 * @Date 2022/6/28 19:02
 * @Description: 8. 字符串转换整数 (atoi) victory
 */
public class Demo07 {
    public static void main(String[] args) {
//        System.out.println(4365 / 100.0);
//        System.out.println(Character.digit('0', 10));
        System.out.println(myAtoi("-91283472332"));
        //System.out.println(Double.parseDouble("-43.234"));
    }

    public static int myAtoi(String s) {
        if ("".equals(s.trim())) return 0;
        char[] chars = s.trim().toCharArray();
        long n = 0;
        //标记负数
        int i = 0, flag = 0;
        if (!Character.isDigit(chars[i])) {
            if (chars[i] == '-') {
                flag = 1;
            } else {
                if (chars[i] != '+') return 0;
            }
            i++;
        }
        for (; i < chars.length; i++) {
            //判断是否为数字
            if (Character.isDigit(chars[i])) {
                n = n * 10 + Character.digit(chars[i], 10);
                if (flag == 0 && n > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
                if (flag == 1 && -n < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
            } else {
                break;
            }
        }
        n = flag == 0 ? n : -n;
        return (int) n;
    }
}

9. 回文数

/**
 * @Author Tiam
 * @Date 2022/6/29 8:12
 * @Description: 9. 回文数  victory
 */
public class Demo08 {
    public static void main(String[] args) {
        System.out.println(isPalindrome(121));
    }

    public static boolean isPalindrome(int x) {
        if (x < 0) return false;
        int n = 0, m = x;
        while (x > 0) {
            n = n * 10 + x % 10;
            x /= 10;
        }
        return m == n ? true : false;
    }
}

704. 二分查找

/**
 * @Author Tiam
 * @Date 2022/6/29 8:41
 * @Description:   704. 二分查找  victory
 */
public class Demo09 {
    public int search(int[] nums, int target) {
        int low = 0,high = nums.length-1,mid;
        while (low<=high){
            mid = (low + high)/2;
            if(nums[mid]>target)
                high = mid - 1;
            else if(nums[mid]<target)
                low = mid + 1;
            else
                return mid;
        }
        return -1;
    }
}

278. 第一个错误的版本

/**
 * @Author Tiam
 * @Date 2022/6/29 8:47
 * @Description: 278. 第一个错误的版本   false false true true true
 *                                  victory
 */
public class Demo10 {
    public static void main(String[] args) {
        System.out.println(firstBadVersion(2126753390));
    }

    public static int firstBadVersion(int n) {
        long low = 1, high = n, mid;
        while (low <= high) {
            mid = (low + high) / 2;
            if (isBadVersion((int) mid) && !isBadVersion((int) mid - 1))
                return (int) mid;
            else if (isBadVersion((int) mid)) {
                high = mid - 1;
            } else
                low = mid + 1;
        }
        //无解抛出异常
        throw new IllegalArgumentException("The equation has no solution");
    }

    static boolean isBadVersion(int n) {
        if (n >= 1702766719)
            return true;
        else
            return false;
    }
}

35. 搜索插入位置

/**
 * @Author Tiam
 * @Date 2022/6/29 10:01
 * @Description: 35. 搜索插入位置  victory
 *                   在升序数组nums中,寻找target,找到返回其下标,没找到返回其待插入的位置。
 */
public class Demo11 {
    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 6};
        int target = 4;
        System.out.println(searchInsert(nums, target));
    }

    public static int searchInsert(int[] nums, int target) {
        int low = 0, high = nums.length - 1, mid;
        while (low <= high) {
            mid = (low + high) / 2;
            if (nums[mid] > target)
                high = mid - 1;
            else if (nums[mid] < target)
                low = mid + 1;
            else
                return mid;
        }
        return low;
    }
}

删除排序数组中的重复项

/**
 * @Author Tiam
 * @Date 2022/6/29 12:23
 * @Description:  删除排序数组中的重复项  victory
 */
public class Demo12 {
    public static void main(String[] args) {
        int[] nums = {0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
        System.out.println(removeDuplicates_(nums));
    }

    public static int removeDuplicates(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length - count - 1; ) {
            if (nums[i] == nums[i + 1]) {
                for (int j = i + 1; j < nums.length - count - 1; j++) {
                    nums[j] = nums[j + 1];
                }
                count++;
            } else i++;
        }
        return nums.length - count;
    }
    /** 方式二 */
    public static int removeDuplicates_(int[] nums) {
        int p = 0, q = 1;
        for(;q < nums.length;q++)
            //寻找右指针与当前p不同的值, 存储到p的下一位.
            if(nums[p] != nums[q]) nums[++p] = nums[q];
        return ++p;
    }
}

买卖股票的最佳时机 II

/**
 * @Author Tiam
 * @Date 2022/6/29 13:01
 * @Description: 买卖股票的最佳时机 II   victory
 */
public class Demo13 {
    public static void main(String[] args) {
        //int[] nums = {1,2,3,4,5};
        //int[] nums = {7,1,5,3,6,4};
        //int[] nums = {7,6,4,3,1};
        int[] nums = {2, 1, 2, 0, 1};
        System.out.println(maxProfit(nums));

    }

    public static int maxProfit(int[] prices) {
        // -1 标记未购入
        int in = -1, rise = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            if (prices[i + 1] > prices[i] && in == -1)
                in = prices[i];
            if (prices[i + 1] < prices[i] && in != -1) {
                rise += prices[i] - in;
                in = -1;
            } else if (i + 1 == prices.length - 1 && in != -1) {
                rise += prices[i + 1] - in;
                in = -1;
            }
        }
        return rise;
    }
}

实现 pow(x, n)

/**
 * @Author Tiam
 * @Date 2022/6/29 14:38
 * @Description: 实现 pow(x, n) ,即计算 x 的整数 n 次幂函数(即,xn )。
 */
public class Demo14 {
    public static void main(String[] args) {
        System.out.println(myPow(2.00000, -2147483648));
        System.out.println(myPow_(5, -1));
    }
    /** x的n次方,适用于正整数求幂 */
    public static int myPow_(int x, int n) {
        int r = 1;
        while (n > 1) {
            if ((n & 1) == 1) r *= x;
            x *= x;
            n >>= 1;
        }
        return r * x;
    }

    public static double myPow(double x, int n) {
        //特殊情况
        if (x == 1) return 1;
        if (x == 0) return 0;
        if (x == -1) return n % 2 == 0 ? 1 : -1;
        if (n == Integer.MIN_VALUE) return 0.0;
        int flag = 0;
        if (n < 0) {
            n = -n;
            flag = 1;
        }
        double res = 1.0;
        for (int i = 0; i < n; i++) {
            res *= x;
        }
        return flag == 0 ? res : 1 / res;
    }
}

存在重复元素,返回true,否则 false

/**
 * @Author Tiam
 * @Date 2022/6/30 8:28
 * @Description:  存在重复元素,返回true,否则 false
 */
public class Demo15 {
    public static void main(String[] args) {
        int[] nums = {1,2,3,4};
        System.out.println(containsDuplicate_1(nums));
    }
    public static boolean containsDuplicate(int[] nums) {
        for (int i = 0; i<nums.length;i++){
            for (int j = i+1; j < nums.length; j++) {
                if(nums[j] == nums[i])
                    return true;
            }
        }
        return false;
    }
    public static boolean containsDuplicate_(int[] nums) {
        // 先排序后,重复的元素会相邻
        Arrays.sort(nums);
        for (int i = 0; i<nums.length-1;i++){
            if(nums[i] == nums[i+1])
                return true;
        }
        return false;
    }
    /**
     * set集合不能含有重复元素
     * add 添加元素时,如含有重复元素则添加失败返回 false
     * 较上面效率更高
     */
    public static boolean containsDuplicate_1(int[] nums) {
        HashSet<Object> objects = new HashSet<>();
        for(int i: nums){
            if(!objects.add(i))
                return true;
        }
        return false;
    }
}

977. 有序数组的平方

/**
 * @Author Tiam
 * @Date 2022/6/30 9:00
 * @Description: 977. 有序数组的平方
 */
public class Demo16 {
    public static void main(String[] args) {
        System.out.println(5);
    }
    public int[] sortedSquares(int[] nums) {
        int[] squares = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            squares[i] = nums[i] * nums[i];
        }
        Arrays.sort(squares);
        return squares;
    }

    public int[] sortedSquares_(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] *= nums[i];
        }
        Arrays.sort(nums);
        return nums;
    }
}

189. 轮转数组

/**
 * @Author Tiam
 * @Date 2022/6/30 9:30
 * @Description: 189. 轮转数组
 */
public class Demo17 {
    public static void main(String[] args) {
        int[] nums = {0, 1, 2, 3};
        rotate(nums, 2);
        System.out.println(Arrays.toString(nums));
    }

    /**
     * 超时 overtime
     */
    public void rotate_(int[] nums, int k) {
        int temp;
        for (int i = 0; i < k; i++) {
            temp = nums[nums.length - 1];
            for (int j = nums.length - 1; j > 0; j--) {
                nums[j] = nums[j - 1];
            }
            nums[0] = temp;
        }
    }

    public static void rotate(int[] nums, int k) {
        // 复制数组
        int[] nums_ = Arrays.copyOf(nums, nums.length);
        for (int i = 0; i < nums.length; i++) {
            int j = i + k;
            if (j > nums.length - 1) j %= nums.length;
            nums[j] = nums_[i];
        }
    }
}
相关文章
|
存储 编译器 数据库
【C/C++ 数据结构 】线索二叉树全解析:从数学原理到C++实现
【C/C++ 数据结构 】线索二叉树全解析:从数学原理到C++实现
971 0
|
10月前
|
弹性计算 人工智能 数据安全/隐私保护
2026年零基础阿里云ECS云服务器部署OpenClaw(Clawdbot)及skills喂饭级教程
2026年,OpenClaw(原Clawdbot、Moltbot)凭借“自然语言驱动+全场景自动化+零代码门槛”的核心优势,成为开源AI智能体赛道的标杆项目,GitHub星标数突破18万+,吸引了无数零基础用户和企业团队尝试部署使用。它就像一个24小时无休、任劳任怨的专属AI打工仔,不用发工资、不抱怨、不摸鱼,一句话下达指令,就能自动完成邮件处理、文件整理、代码生成、定时任务、全网搜索等所有重复工作,真正实现“人在摸鱼,工作已完成”的理想状态。
1324 1
|
11月前
|
人工智能 运维 监控
智能体来了·智创未来:AI 智能体成为数字时代的新型基础设施
AI智能体正从单点工具升级为可持续运行的平台型基础设施,具备通用认知、自主执行与协同扩展能力,可复用嵌入各类业务系统。它正成为数字经济底座,推动AI从项目制应用迈向普惠化、系统化能力供给。(239字)
320 2
|
11月前
|
存储 人工智能 机器人
2026年5款高转化AI语音机器人盘点:智能导购选哪家?
本文深度评测2026年主流AI语音机器人,聚焦智能导购场景,从大模型理解力、真人感交互及部署成本等维度,为您筛选出能显著提升转化率的选型方案,助企业在数字化转型中抢占先机。
|
存储 Java Linux
详细地说一说零拷贝
我是小假 期待与你的下一次相遇 ~
912 1
详细地说一说零拷贝
|
缓存 Java 测试技术
高德?不,用自己的导航
编写该文章的目的是在开发时需要用到自定义的路网导航,查阅高德、百度地图等相关网站后,并没有发现可自定义路网的导航,后来在Git上搜到了Graphhopper这个国外的开源软件,然后学习使用后实现了自定义路网导航的功能,现在记录一下自己的实现过程,以保存开发资料,并且帮助到需要实现相关功能的朋友。
972 1
|
缓存 监控 供应链
当当平台商品详情接口开发指南:从接入到实战
当当网开放平台提供商品详情接口(dangdang.item.get),支持获取图书商品的基础信息、价格、库存、多媒体等数据,适用于价格监控、库存管理、推荐系统等场景。开发者需注册账号、创建应用并申请接口权限,通过API调用实现商品数据获取与管理。
|
人工智能 算法 机器人
人工智能浪潮下的人类社会:重构秩序,还是共舞未来?
人工智能正以前所未有的速度改变社会结构,从工具变为行为参与者。它不仅提升效率,更具备学习、生成与决策能力,重塑就业、法律、财富分配乃至国家治理模式。面对AI风暴,唯有制度创新与全民共享,方能避免技术垄断与社会失衡。
644 0
|
设计模式 Java API
05.接口隔离原则介绍
接口隔离原则(ISP)是SOLID原则之一,强调客户端不应依赖于它们不需要的接口。通过将庞大而臃肿的接口拆分为更小、更具体的接口,确保每个接口只包含客户端真正需要的方法,从而提高代码的可维护性和灵活性。本文详细介绍了接口隔离原则的概念、核心思想、实现方式及案例分析,并对比了其与单一职责原则的区别。关键点包括:接口应精简、独立且可扩展,避免强迫实现不必要的方法,减少系统的耦合性。
718 19
|
人工智能 自然语言处理
使用企业微信或公众号自动回复图片消息
AppFlow支持企业微信和公众号接收图片消息,并提供两种回复方式。方式一:直接回复图片消息,用户发送图片后立即收到回复,但无法继续追问。方式二:先保存图片,待用户发送文字后再一并处理并回复。配置步骤包括选择模板、配置鉴权信息、设置执行动作参数及发布连接流。详细操作可参考相关文档。
2186 1
使用企业微信或公众号自动回复图片消息