一、两数之和
原题链接
- 给定一个整数数组
nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
- 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
- 你可以按任意顺序返回答案。
Python解法
1、暴力解法
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#获取nums数组的长度
n = len(nums)
#两次循环
for i in range(n - 1):
for j in range(i + 1, n):
if target == nums[i] + nums[j]:
return [i, j]
#若是没有找到则返回[]空列表
return []
2、dict集合(哈希表)解法
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#创建一个空dict集合
num_to_index = dict()
#使用enumerate()方法获取nums数组的 (索引,值)的迭代器对象,并进行遍历
for index,num in enumerate(nums):
complement = target - num #计算与当前数字匹配的补数
if complement in num_to_index:
return [num_to_index[complement], index] # 找到补数在哈希表中的索引,以及当前数字的索引
num_to_index[num] = index # 将当前数字添加到哈希表中
return [] # 如果没有找到匹配的组合,返回空列表
Java解法
1、暴力解法
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for(int i = 0; i < n - 1; i++){
for(int j = i + 1; j < n; j++){
if(nums[i] + nums[j] == target){
return new int[]{i, j};
}
}
}
return new int[]{};
}
}
2、HashMap集合(哈希表)解法
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (hashMap.containsKey(complement)) {
return new int[]{hashMap.get(complement), i};
}
hashMap.put(nums[i], i);
}
return new int[]{};
}
}
二、两数相加
原题链接
- 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
- 请你将两个数相加,并以相同形式返回一个表示和的链表。
- 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
Python解法
class ListNode(object):
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
virtual_head = ListNode()
current = virtual_head
carray = 0
while l1 is not None or l2 is not None or carray != 0:
val1 = l1.val if l1 is not None else 0
val2 = l2.val if l2 is not None else 0
total = val1 + val2 + carray
carray = total // 10
current.next = ListNode(total % 10)
current = current.next
if l1 is not None:
l1 = l1.next
if l2 is not None:
l2 = l2.next
return virtual_head.next
def print_list(self,head):
while head is not None:
print(head.val," -> ",end="")
head = head.next
print("None")
def main(self):
l1 = ListNode(9,ListNode(9))
l2 = ListNode(1,ListNode(1))
self.print_list(self.addTwoNumbers(l1, l2))
if __name__ == '__main__':
s = Solution()
s.main()
Java解法
/**
* 单链表中的节点:
* 节点是单链表中的基本单元
* 每一个节点Node都有两个属性
* 一个属性:是存储的数据
* 另一个属性:是下一个节点的内存地址
*/
class ListNode {
//实例变量 val 存储的数据
int val;
//实例变量 next 下一个节点的引用(内存地址)
ListNode next;