LeetCode刷题(一)

1. Two Sum

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, 
return [0, 1].

思路及代码

  1. 第一种方法:简单粗暴直接遍历数组找出两个数对应的下标返回,这里可以用两个指针,一个i从数组下标为0的位置开始遍历到倒数第二个元素,第二个指针始终指向i的下一个位置,对应的Python代码如下。
class Solution(object):
	def twoSum(self, nums, target):
	    """
	    :type nums: List[int]
	    :type target: int
	    :rtype: List[int]
	    """
	    n = len(nums)
	    res = []
	    for i in range(n - 1):
	        for j in range(i + 1, n):
	            if (nums[i] + nums[j] == target):
	                res.append(i)
	                res.append(j)
	    return res
  1. 第二种方法:根据target值,使用一个指针i,遍历数组,用target值减去nums[i]然后得到另一个元素的值,利用index函数查找下标为 i + 1 i+1 i+1之后的数组中是否存在该元素,若存在直接返回下标,不存在则继续下一次循环,对应的Python代码如下。
class Solution(object):
	def twoSum(self, nums, target):
	    """
	    :type nums: List[int]
	    :type target: int
	    :rtype: List[int]
	    """
	    n = len(nums)
        res = []
        for i in range(n - 1):
            sub = target - nums[i]
            if sub in nums[i + 1:]:
                res.append(i)
                res.append(nums.index(sub, i + 1))
        return res
  1. 第三种方法:第二种方法用的是target - nums[i] 的方法,同样的这里也是,我们将target - nums[i] 的值作为键,i对应的下标作为值,然后遍历一遍nums数组,当数组中的某个元素是哈希表中的键,而且该键对应的值不等于此时数组的下标位置时,我们就找到了和为target的两个不重复位置的元素,对应的Python代码如下。
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashTab = {target - num: i for i, num in enumerate(nums)}
        for i, num in enumerate(nums):
            if (num in hashTab) and (i != hashTab[num]):
                return list((i, hashTab[num]))

2. Add Two Numbers

Description

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

思路及代码

  1. 第一种方法:简单粗暴直接将链表转换为数字之后,两个数字相加得到的结果再存入链表中。具体的Python代码如下:
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        num1 = []
        num2 = []
        Num1 = 0
        Num2 = 0
        while l1:
            num1.append(l1.val)
            l1 = l1.next
        while l2:
            num2.append(l2.val)
            l2 = l2.next
        for i in range(len(num1)):
            Num1 += num1[i] * (10 ** i)
        for j in range(len(num2)):
            Num2 += num2[j] * (10 ** j)
        total = Num1 + Num2
        newNode = ListNode(0)
        head  = newNode
        while total >= 10:
            head.next = ListNode(total % 10)
            head = head.next
            total = total / 10
        head.next = ListNode(total % 10)
        return newNode.next
  1. 第二种方法:设置一个代表进位的值tag,创建一个新的结点,结点初始值设置为0,然后遍历链表,在两个链表都不为空的情况下,将两个链表对应的值和tag进位值三者相加,得到的值 v a l u e % 10 value \% 10 value%10即为存入新结点的值, t a g = v a l u e / 10 tag = value / 10 tag=value/10,若value小于10,tag的值为0,若value刚好为10, v a l u e % 10 = 0 value \% 10 = 0 value%10=0。此外我们需要考虑链表长度不同的情况,对于不为空的链表,按照前面的方法存入新的结点,不同的是最后的tag进位值,遍历完两个链表后需要查看最后的tag值,若tag不为0,则需要将tag值存入新的结点。具体的Python代码如下:
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        newNode = ListNode(0)
        head = newNode
        tag = 0
        while l1 and l2:
            value = l1.val + l2.val + tag
            head.next = ListNode(value % 10)
            tag = value / 10
            l1 = l1.next
            l2 = l2.next
            head = head.next
        cur = l1
        if l2 != None:
            cur = l2
        while cur:
            value = cur.val + tag
            head.next = ListNode(value % 10)
            tag = value / 10
            cur = cur.next
            head = head.next
        if (tag != 0):
            head.next = ListNode(tag)
        return newNode.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值