美文网首页
[数组问题]

[数组问题]

作者: 周闖 | 来源:发表于2020-01-17 22:08 被阅读0次

66. 加一

题目描述

给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。

示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。

示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/plus-one

解题思路

  • 方法1. 将列表倒序遍历,如果数字是9则将9变为0,就如果不是则加1并跳出循环(如果遍历到第一个则说明是99...99这种情况,则在第一个数字插入1)
  • 方法2. 将列表中的数直接转换为数字(通过十进制加法),然后加一,再转换为列表
  • 方法3. Python独有的奇技淫巧.

代码实现

  • 方法1.
class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        for i in range(len(digits)-1, -1, -1):
            if digits[i] == 9:
                digits[i] = 0
                if i == 0:
                    digits.insert(0, 1)
            else:
                digits[i] += 1
                break
        return digits
  • 方法2.
class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        sums = 0
        for i in digits:
            sums = sums * 10 + i
        sums_str = str(sums + 1)
        return [int(j) for j in sums_str]
  • 方法3.
class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        return [int(x) for x in str(int(''.join([str(i) for i in digits])) + 1)]

88. 合并两个有序数组

题目描述

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

说明:

初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3

输出: [1,2,2,3,5,6]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-sorted-array

解题思路

  • 方法1: 先合并,然后排序
  • 方法2: 双指针

代码实现

  • 方法1.
class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        nums1[:] = sorted(nums1[:m] + nums2[:n])

相关文章

  • [数组问题]

    34. 在排序数组中查找元素的第一个和最后一个位置 题目描述 给定一个按照升序排列的整数数组 nums,和一个目标...

  • [数组问题]

    66. 加一 题目描述 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。最高位数字存放在数组的首...

  • JS问题记录

    一、数组问题 1、数组添加元素 2、数组删除指定下标元素 3、数组排序

  • java笔记5

    数组的定义 数组的内存分配及特点 数组操作常见问题 数据常见操作 数组中的数组 @Test public void...

  • 类数组问题

    类数组长什么样子? 类数组怎么转化为数组呢? 1.使用 Array.prototype.slice.call(【类...

  • 指针数组问题

    指针数组问题 这里的ar其实和&ar[0]是等价的,是一个地址常量,可以使用ar+1标志下一个元素,但不能使用ar++

  • 数组拷贝问题

    今天做一个购物车时用到了mutableCopy,发现发mutableCopy虽然对外层数组进行了拷贝,但是内层对象...

  • 数组基础问题

    1.Sum of the array numbers 2.Minimum element of the array...

  • 数组循环问题

    自测-3 数组元素循环右移问题一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移...

  • 数组越界问题

    等价于 要想让a6输出的结果为6,将for循环的var改成let即可,修改代码如下: 关于var 和 let 区别...

网友评论

      本文标题:[数组问题]

      本文链接:https://www.haomeiwen.com/subject/jxjhzctx.html