Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

python - Partition Array

Given an array nums of integers and an int k, partition the array (i.e move the elements in nums) such that: All elements < k are moved to the left. All elements >= k are moved to the right Return the partitioning index, i.e the first index i nums[i] >= k.

class Solution:
    def partitionArray(self, nums, k):
        # write your code here
        if nums == []:
            return 0
        left = 0
        i = 0
        while i <= len(nums):
            if nums[i] < k:
                i += 1
                left += 1
            else:
                r = nums[i]
                del nums[i]
                nums.append(r)
                i += 1

        return left

My idea is to going through the list one by one. The num[i] whose larger than k will be removed and append at the end of the num, the one whose smaller than k will be kept at the original place. Once the whole list has been going through, all the smaller num are at the front. left is a counter at this point for return. But I cannot fix the problem with nums[i]. After the each mods to the list, the counter i cannot point at the correct item in the list.

How can I write the code base on this idea???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're looking for the index(k). This seems like a homework assignment so you may be limited to what built in functionality you can use. However, a pythonic approach to this is

def solution(nums, k):
    return sorted(nums).index(k)

You are doing several things I would recommend avoiding.

  1. Concurrent modification; you should not add or delete from a list while looping it.
  2. You can not loop up to i == len(nums) because list indexes start at 0.

Since you are really just looking for index(k) you need only keep track of numbers less than k and not concern yourself with re-organizing the list.

class Solution:
    def partitionArray(self,nums, k):
        # write your code here
        if nums == []:
            return 0
        left = 0
        i = 0
        while i < len(nums):
            if nums[i] < k:
                left += 1
            i += 1

        return left

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...