zoukankan      html  css  js  c++  java
  • 31. 数组划分

    31. 数组划分

    中文English

    给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:

    • 所有小于k的元素移到左边
    • 所有大于等于k的元素移到右边

    返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k

    样例

    例1:

    输入:
    [],9
    输出:
    0
    
    

    例2:

    输入:
    [3,2,2,1],2
    输出:1
    解释:
    真实的数组为[1,2,2,3].所以返回 1
    

    挑战

    使用 O(n) 的时间复杂度在数组上进行划分。

    注意事项

    你应该真正的划分数组 nums,而不仅仅只是计算比 k 小的整数数,如果数组 nums 中的所有元素都比 k 小,则返回 nums.length。

     
     
    输入测试数据 (每行一个参数)如何理解测试数据?
    class Solution:
        """
        @param nums: The integer array you should partition
        @param k: An integer
        @return: The index after partition
        """
        '''
        大致思路:背向型双指针
        1.小于的话丢左边,大于的话丢右边,最终left就是所要放置的位置
        '''
        def partitionArray(self, nums, k):
            #初始化
            length = len(nums)
            left, right = 0, length - 1
            index = 0 
    
            #left指针指向比k小的数,right指针指向的是比k大的数,第三个指针默认走
            while index <= right:
                if (nums[index] < k):
                    nums[left], nums[index] = nums[index], nums[left]
                    left += 1
                    index += 1
                elif (nums[index] > k):
                    nums[right], nums[index] = nums[index], nums[right]
                    right -= 1
                else:
                    index += 1
                    continue
            
            return left
  • 相关阅读:
    C#代码常用技巧
    MVC
    json类型
    android 上传二进制文件的两种方式
    BroadcastReceiver 使用goAsync 执行异步操作
    android组件间通信又一种方式
    Android BLE基础框架使用详解
    Android BLE设备蓝牙通信框架BluetoothKit
    android studio ndk开发总结
    jni c基础总结
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13199828.html
Copyright © 2011-2022 走看看