leetcode 75. Sort Colors-颜色排序|双指针

原创 2016年06月01日 15:48:15
原题链接:75. Sort Colors

【思路1-Python】-双指针|T=O(n)|M=O(1)

申请两枚指针,head 和 tail,用 i 进行遍历,当 num[i] == 0时,交换当前位置和头指针处值,当 nums[i] == 2时,交换当前位置和尾指针处值,当 nums[i] == 1时,不进行交换:

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        head, tail, i = 0, len(nums)-1, 0
        while i <= tail :
            if nums[i] == 0 :
                nums[i], nums[head] = nums[head], nums[i]
                head += 1
                i += 1
            elif nums[i] == 1 : i += 1
            else : 
                nums[i], nums[tail] = nums[tail], nums[i]
                tail -= 1
86 / 86 test cases passed. Runtime: 52 ms  Your runtime beats 46.69% of pythonsubmissions.

【思路2-Java】-双指针|T=O(n)|M=O(n)

申请一个数组,初始化数组值为1,也是用双指针。当 num[i] == 0时,覆盖头指针处值,当 nums[i] == 2时,覆盖尾指针处值,当 nums[i] == 1时,不覆盖,最后将新数组的值覆盖旧数组:

public class Solution {
    public static void sortColors(int[] nums) {
        int len = nums.length;
        int[] tmp = new int[len];
        for(int i = 0; i < len; i++)      //初始化数组为1
            tmp[i] = 1;
        int first = 0, last = len - 1;
        for(int i=0; i<len; i++)          //遍历一次
            if(nums[i] == 0) tmp[first++] = 0;
            else if(nums[i] == 2) tmp[last--] = 2;
        for(int i=0; i<len; i++) nums[i] = tmp[i];
    }
}
86 / 86 test cases passed. Runtime: 1 ms  Your runtime beats 4.38% of javasubmissions.

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode-75. Sort Colors (JAVA)三色排序

LeetCode-75. Sort Colors (JAVA)三色排序

leetcode-75 Sort Colors

因为待排序的数字的大小在一个很小的范围之内(0-2),所以可以使用这种算法: A rather straight forward solution is a two-pass algorithm u...

[leetcode] 75. Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same colo...

LCP075 LeetCode 75. Sort Colors

Total Accepted: 100513 Total Submissions: 287992 Difficulty: Medium Given an array with n...

Leetcode 75:Sort Colors

Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of ...

leetcode:75. Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same colo...

Leetcode75 - Sort Colors(two pointers)

题意给定一个数组,只包含0,1,2,将0,1,2按照顺序排列。要求: 1. 只能开常数空间 2. 对数组只扫描一遍思路算法1算法1是最容易想到的,我们扫描一遍数组统计一下每个数字的数目,然后再扫描...
  • Lzedo
  • Lzedo
  • 2017-01-19 23:17
  • 87

[leetcode] 75. Sort Colors 解题报告

题目链接:https://leetcode.com/problems/sort-colors/ Given an array with n objects colored red, white o...

LeetCode 75 Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same colo...

LeetCode(75)Sort Colors (荷兰三色旗问题 Dutch National Flag)

题目如下: The flag of the Netherlands consists of three colours: red, white and blue. Given balls of the...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)