I tried LeetCode every day 1. Two Sum (Python, Go)

Introduction

@Ishishow is running a free English word site E-tan.

I would like to work on letcode every day to improve my ability as a programmer and give my own way of solving it.

What is Leetcode

leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.

Introduction to Go language + algorithm I will solve it with Golang and Python to strengthen my brain. (Python is weak but experienced)

First day

Two Sum

--Problem content (Japanese translation)

If an array of integers and an integer are given nums`` target, * the sum is target *. * Returns * an index of two numbers so that it becomes *.

You can assume that each input has *** exactly \ * one solution **, and you cannot use the * same * element twice.

Answers can be returned in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: 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]

This problem seemed to be good if I assigned a value to the dictionary type and finished the process when (Target-value) existed.

By the way, I first described the loop processing twice in the full search, but I got a RunTimeError and saw the answer. .. ..

Python looping is slow. ..

--Answer code

  class Solution(object):
      def twoSum(self, nums, target):
          d = {} 
          for i in range(len(nums)):
              if (target - nums[i]) in d:
                  return [d[target - nums[i]],i]
              else:
                  d[nums[i]] = i
          return 0

--My first code (gets RunTimeError)

  class Solution(object):
      def twoSum(self, nums, target):
          a = len(nums)
          for i in range(a):
              j = i+1
              while j!=a:
                  if nums[i] + nums[j] == target:
                      return [i,j]
                  j +=1
          return 0
                  

Since an error occurred, the painful processing of setting a = len (nums) was also empty, so I rewrote it in dictionary type. .. ..

--I'll write it in Go too!

  func twoSum(nums []int, target int) []int {
  	m := make(map[int]int)
  	for i, v := range nums {
  		idx, ok := m[target-v]
  		if ok {
  			return []int{idx, i}
  		}
  		m[v] = i
  	}
  	return nil
  }

With Go, the execution time was completely different!

--Self memo (Go)

Reasons to use make

If you do not specify an initial value for Maps (associative array), the variable is initialized to nil (nil map). nil map cannot store elements, and if you want to store elements, you need to initialize the map.

	idx, ok := m[target-v]

If there is that value, True is entered in ok.

Go often uses slices because the array has a fixed length.

Since the writing method of Go is ambiguous, I am doing it while investigating, but it seems that if I finish this, I will gain considerable ability!

Referenced articles

[Go] Basic Grammar ⑤ (Associative Array / Range)

Go language: Summary of how to make various maps

Recommended Posts

I tried LeetCode every day 1. Two Sum (Python, Go)
I tried LeetCode every day 167. Two Sum II --Input array is sorted (Python, Go)
I tried LeetCode every day 136. Single Number (Python, Go)
I tried LeetCode every day 118. Pascal's Triangle (Python, Go)
I tried LeetCode every day 125. Valid Palindrome (Python, Go)
I tried LeetCode every day 155. Min Stack (Python, Go)
I tried LeetCode every day 9. Palindrome Number (Python, Go)
I tried LeetCode every day 160. Intersection of Two Linked Lists (Python, Go)
I tried LeetCode every day 141. Linked List Cycle (Python, Go)
I tried LeetCode every day 110. Balanced Binary Tree (Python, Go)
I tried LeetCode every day 14.Longest Common Prefix (Python, Go)
I tried LeetCode every day 168. Excel Sheet Column Title (Python, Go)
I tried LeetCode every day 111. Minimum Depth of Binary Tree (Python, Go)
I tried LeetCode every day 26. Remove Duplicates from Sorted Array (Python, Go)
I tried LeetCode every day 108. Convert Sorted Array to Binary Search Tree (Python, Go)
I tried LeetCode every day 122. Best Time to Buy and Sell Stock II (Python, Go)
I tried Grumpy (Go running Python).
I tried running faiss with python, Go, Rust
I tried Python> decorator
I tried fp-growth with python
I tried scraping with Python
I tried Python C extension
[Python] I tried using OpenPose
I tried gRPC with Python
I tried scraping with python
I tried to touch Python (installation)
I tried web scraping with python.
I tried using Thonny (Python / IDE)
I tried running prolog with python 3.8.2.
I tried Line notification in Python
I tried SMTP communication with Python
[Python] I tried using YOLO v3
I tried to summarize Python exception handling
I tried to implement PLSA in Python
I tried to implement permutation in Python
I tried scraping Yahoo News with Python
I tried to implement PLSA in Python 2
Python3 standard input I tried to summarize
I tried sending an email with python.
I tried using Bayesian Optimization in Python
I tried non-photorealistic rendering with Python + opencv
I tried using UnityCloudBuild API from Python
I tried to implement ADALINE in Python
I tried recursion with Python ② (Fibonacci sequence)
I tried to implement PPO in Python
Python: I tried the traveling salesman problem
Wrangle x Python book I tried it [1]
Mayungo's Python Learning Episode 8: I tried input
[Python] I tried to calculate TF-IDF steadily
I tried scraping Yahoo weather (Python edition)
I tried to touch Python (basic syntax)
I tried the Python Tornado Testing Framework
#I tried something like Vlookup with Python # 2
I tried running two Jetson Nano hardware PWMs from the Jetson.GPIO Python library.
[LIVE] I tried to deliver the sunrise and sunset times nationwide every day
Python day 1
[Baseball Hack] I tried copying the Python MLB score & grade data acquisition script with Go in half a day
[Python / DynamoDB / boto3] List of operations I tried
I tried "smoothing" the image with Python + OpenCV
I tried hundreds of millions of SQLite with python
vprof --I tried using the profiler for Python