LeetCode Challenge (Python3). Problem#1

leetcode

Source

I recently decided to improve my programming skills, so I decided to use LeetCode to achieve this goal.

However, since I don't have much programming experience and this is my first time using LeetCode, there may be some struggles in the process, but I believe I will be able to persevere.

There are currently 2230 problems on LeetCode, and I will be working on the challenge by problem number with the goal of solving all of them.

Let's start today's question!


Today's question is "1. Two Sum".

Problem url: https://leetcode.com/problems/two-sum/

Difficulty: Easy
Related Topics: Array Hash Table

Problem:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]


Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

My solution:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if nums.count(target/2)==2 : # Determine if the situation is the same as Example 3
            n1=nums.index(target/2) # Find num1
            for i in range (n1+1,len(nums)): # Find num2
                if nums[i]==target/2:
                    n2=i
                    return n1,n2
        else: # Situations other than Example 3
            for i in range(len(nums)):
                if nums[i] in nums and (target-nums[i]) in nums and nums[i]!=(target-nums[i]):
                    n1=nums.index(nums[i]) # Find num1
                    n2=nums.index(target-nums[i]) #Find num2
                    return n1,n2

After coding, I submitted my solution.

image.png


This is the end of the leetcode challenge.

Feel free to give some suggestions based on my code, whether it's a way to improve performance or shorten the code.

Thanks for stopping by here and reading my post.

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center