Personal post 6 hours ago
【# 1. 两数之和
Chính chủ gửi cần bán gấp nhà mới xây tại phường Bửu Hòa, TP. Biên Hòa
• Vị trí đẹp, cách Công ty Pouchen chỉ 5-10 phút, tiện ích xung quanh đầy đủ
• Nhà mới xây, kết cấu hiện đại, vào ở ngay
• Thiết kế gồm: 1 phòng khách, 3 phòng ngủ, 1 WC
• Đường ô tô vào tận nhà, giao thông thuận tiện
Sổ chung
Diện tích: 5.3 x 15m (79.5m²)
Giá bán: 1 tỷ 550 triệu (còn thương lượng cho khách thiện chí)
Liên hệ: ***
【# 1. 两数之和
## 题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
```text
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
```
> 来源:力扣(LeetCode)
> 链接:<https://leetcode-cn.com/problems/two-sum>
> 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
---
## 暴力法
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
```
运行结果:
> 执行结果:通过
> 执行用时:40 ms, 在所有 Python3 提交中击败了70.00% 的用户
> 内存消耗:14.6 MB, 在所有 Python3 提交中击败了5.48% 的用户
---
## 哈希表
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, num in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[num] = i
```
运行结果:
> 执行结果:通过
> 执行用时:40 ms, 在所有 Python3 提交中击败了70.00% 的用户
> 内存消耗:14.6 MB, 在所有 Python3 提交中击败了5.48% 的用户
---
## 哈希表(使用 `dict.get` 方法)
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, num in enumerate(nums):
j = d.get(target - num)
if j is not None:
return [j, i]
d[num] = i
```
运行结果:
> 执行结果:通过
> 执行用时:40 ms, 在所有 Python3 提交中击败了70.00% 的用户
> 内存消耗:14.6 MB, 在所有 Python3 提交中击败了5.48% 的用户
---
## 哈希表(使用 `dict.setdefault` 方法)
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, num in enumerate(nums):
j = d.setdefault(target - num, None)
if j is not None:
return [j, i]
d[num] = i
```
运行结果:
> 执行结果:通过
> 执行用时:40 ms, 在所有 Python3 提交中击败了70.00% 的用户
> 内存消耗:14.6 MB, 在所有 Python3 提交中击败了5.48% 的用户
---
## 哈希表(使用 `in` 判断)
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, num in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[num] = i
```
运行结果:
> 执行结果:通过
> 执行用时:40 ms, 在所有 Python3 提交中击败了70.00% 的用户
> 内存消耗:14.6 MB, 在所有 Python3 提交中击败了5.48% 的用户
---
## 总结
- 暴力法的时间复杂度为 $O(n^2)$,空间复杂度为 $O(1)$
- 哈希表的时间复杂度为 $O(n)$,空间复杂度为 $O(n)$
---
`2020.09.12`
Click to show number: 033663****
Loại hình nhà ở:
Nhà ngõ, hẻm
Diện tích sử dụng:
79.5 m²
Giấy tờ pháp lý:
Sổ chung / công chứng vi bằng
Tình trạng nội thất:
Nội thất đầy đủ
Share this post with friends:
Post code: 23449350
This post has been moderated. If you encounter problems, please report the post or contact customer service for help. See more ››