Find Pivot Index之Python实现

一、题目

  Given an array of integers nums, write a method that returns the "pivot" index of this array.

  We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

  If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

  Example 1:

    Input: nums = [1, 7, 3, 6, 5, 6]

    Output: 3

    Explanation: The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.Also, 3 is the first index where this occurs.

  Example 2:

    Input: nums = [1, 2, 3]

    Output: -1

    Explanation: There is no index that satisfies the conditions in the problem statement.

  Note:

    • The length of nums will be in the range [0, 10000].
    • Each element nums[i] will be an integer in the range [-1000, 1000].

二、题目理解

  给定一个整型数组(数组中的值可正可负),寻找数组中的一个值,使得该值左边的所有值之和等于其右边所有值之和,并且该值的下标是所有满足条件的下标中最左边的一个,并返回该值的下标。如果找不到该值,则返回-1。

三、实现代码

1、第一种实现方式

  使用循环遍历数组,每次都计算当前下标左边所有值之和以及右边所有值之和,并判断两个和是否相等,若相等,则返回下标,否则返回-1。实现代码如下:

def solution01(self, nums):
        startTime = time.time()     # 求当前时间
        index = -1
        for i in range(0, len(nums)):
            sum_left = 0
            sum_right = 0
            # 求i左边所有值的和
            for j in range(0, i):
                sum_left += nums[j]
            # 求i右边所有值的和
            for k in range(i + 1, len(nums)):
                sum_right += nums[k]
            # 判断两个和是否相等,相等则跳出循环
            if sum_left == sum_right:
                index = i
                break
        endTime = time.time()       # 求当前时间
        print("程序执行时间:", (endTime - startTime))      #打印程序运行时间(单位:秒)
        return index

 

2、第二种实现方式

  以上的第一种方法的执行时间过长,不是一种好的解决方法,下面是第二种解决方案。

  首先求出整个数组所有值的总和sum,并定义一个变量用于存放当前遍历过的所有值之和cur_sum,再遍历数组,每遍历一个值,都用sum减去当前值,并判断减后的值是否等于cur_sum的2倍,如果是,等当前下标即为所求下标,否则返回-1。

  由于这个方法的循环嵌套较少,运行速度比第一种方法要快。

  实现代码如下:

def solution02(self, nums):
        startTime = time.time()
        index = -1
        sum = 0
        cur_sum = 0
        # 求数组总和
        for i in range(0, len(nums)):
            sum += nums[i]
        for i in range(0, len(nums)):
            temp = sum - nums[i]        # 求总和减去当前值所得的结果
            # 如果temp等于cur_sum的2倍,则返回该下标,否则,算cur_sum的新值
            if temp == cur_sum * 2:
                index = i
                break
            else:
                cur_sum += nums[i]
        endTime = time.time()
        print("程序执行时间:", (endTime - startTime))
        return index

 

源码链接

 

转载于:https://www.cnblogs.com/xiezh-it/p/9711710.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,关于Python实现查找最小的k个数,我可以提供以下两种常见的方法: 方法一:使用堆 将数组前k个元素建立小根堆,然后遍历剩余元素,若比堆顶元素小,则将其加入堆中,同时将堆顶元素删除,最终堆中的k个元素即为所求。具体代码如下: import heapq def find_k_min(nums, k): if not nums or k <= 0 or k > len(nums): return None res = [] for i in range(k): heapq.heappush(res, nums[i]) for i in range(k, len(nums)): if nums[i] < res[0]: heapq.heappop(res) heapq.heappush(res, nums[i]) return res 方法二:使用快排的思想 使用快排的思想,每次选择一个基准元素,将小于基准元素的放在左边,大于等于基准元素的放在右边,然后判断基准元素的位置,若该位置等于k-1,则基准元素以及左边的元素就是所求;若该位置小于k-1,则在右半边继续查找;若该位置大于k-1,则在左半边继续查找。具体代码如下: def find_k_min(nums, k): if not nums or k <= 0 or k > len(nums): return None left, right = 0, len(nums)-1 while True: index = partition(nums, left, right) if index == k-1: return nums[:k] elif index < k-1: left = index + 1 else: right = index - 1 def partition(nums, left, right): pivot = nums[left] while left < right: while left < right and nums[right] >= pivot: right -= 1 nums[left] = nums[right] while left < right and nums[left] < pivot: left += 1 nums[right] = nums[left] nums[left] = pivot return left 希望能对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值