用LeetCode复习Java基本语法(题号75)

Hello Java.

题目描述:
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

注意:
不能使用代码库中的排序函数来解决这道题。

示例:
输入:[2,0,2,1,1,0]
输出:[0,0,1,1,2,2]

进阶:
你能想出一个仅使用常数空间的一趟扫描算法吗?

题目链接:
https://leetcode-cn.com/problems/sort-colors/

最直接的思路:

class Solution {
    public void sortColors(int[] nums) {
        int red = 0;
        int white = 0;
        int blue = 0;
        /* 遍历并统计信息 */
        for (int n : nums) {
            if (n == 0) red++;
            else if (n == 1) white++;
            else blue++;
        }
        int idx = 0;
        /* 依次放置 */
        for (int i = 0; i < red; i++) nums[idx++] = 0;
        for (int i = 0; i < white; i++) nums[idx++] = 1;
        for (int i = 0; i < blue; i++) nums[idx++] = 2;
    }
}

进阶版的思路:

class Solution {
    public void sortColors(int[] nums) {
        if (nums == null || nums.length == 0 || nums.length == 1) {
            return;
        }
        int head = 0;
        int tail = nums.length - 1;
        int curr = 0;
        while (head <= tail && curr <= tail) {
        	/* 当交换的curr值为0时一定排在最前 */
            if (nums[curr] == 0) {
                swap(nums, head++, curr++);
            }
            /* 当交换的curr值为2时有可能换过来的是0需要再次判断curr */
            else if (nums[curr] == 2) {
                swap(nums, tail--, curr);
            }
            else {
                curr++;
            }
        }
    }
    private void swap(int[] nums, int a, int b) {
        if (a == b) {
            return;
        }
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}

Java中的for循环

  • 传统for循环(适用于绝大多数情况)
  • 借助迭代器进行循环(常见于遍历Collection对象)
  • 在JDK1.5中出现的简化方式,又称for-each方式(适用于绝大多数情况,编译期间转换为传统方式,无性能问题)
  • for (int n : nums) ...
  • 在顺序存储时,使用for循环更优;在链式存储时,使用for-each与迭代器循环更优

双指针法

  • 这里的指针并不是传统意义上的指针,可以理解为两个标记,应用于多种算法题目场景

待续ヾ(=・ω・=)o

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值