Hướng dẫn 2 sum leetcode python solution - 2 giải pháp python leetcode tổng hợp
I'm not sure if I'm missing something, but I think not. I ran this code Show
So why do you create the list and then enumerate it? Maybe what you want to do is simply : Also, given your input, there's a possibility that a single number would be higher than the target, in this case you shouldn't make the second iteration. You also don't
need the I'd end up with :
Without knowing the expected input size, it's hard to focus on performance improvements. The main goal of my review was to remove what seemed like a misunderstanding in your code and in my opinion the code is clearer now. Two Sum problem is considered easy and is frequently asked in Amazon phone interviews. We will see how we can start with a brute force solution and try to improve the code by introducing more data structures. Simple Python Calculator (Video 25) Please enable JavaScript Problem Statement: Given an array of integers nums and an integer target return indices of the two numbers such that they add up to target Our aim will be to reduce time complexity and space complexity. The first solution that comes to mind is to go through the loop twice, each loop traverses the list, compares the sum of two numbers with the target, and returns the indices if the sum matches. The time complexity of this algorithm is class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ length = len(nums) for i in range(length): for j in range(i + 1, length): if nums[i] + nums[j] == target: return [i, j] In our next solution, we can check whether the target-num[i] value exists in the rest of the list 0. This is a slightly better solution but still, the time complexity is not 1.class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ length = len(nums) for i in range(length): diff = target - nums[i] if diff in nums[i+1:]: index = nums[i + 1:].index(diff)+i+1 return [i, index] Although the above method is faster than the first one, it is still not the best. Though it looks like we are looping once but in operator loops through the list to search for the diff variable.
Bài Viết Liên QuanQuảng CáoCó thể bạn quan tâmToplist được quan tâm#1
Top 4 uống nước chanh sả mật ong có tác dụng gì 20236 tháng trước#2
Top 10 bài tập làm văn số 5 lớp 7 de 4 20236 tháng trước#3
Top 3 vừa chơi đã có tài khoản vương giả chap 1 20236 tháng trước#4
Top 6 anh sẽ on thôi cover phạm nguyên ngọc lyrics 20236 tháng trước#6
Top 7 hãy ra khỏi người đó đi hợp âm 20236 tháng trước#7
Top 6 giáo án thơ về thăm nhà bác 20236 tháng trước#8
Top 8 giáo án ngữ văn 6 cánh diều 20236 tháng trước#9
Top 9 tinh bột tham gia phản ứng nào 20236 tháng trướcQuảng cáoXem NhiềuQuảng cáoChúng tôiTrợ giúpBản quyền © 2021 Hàng Hiệu Inc.
|