Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to find the integer of the target value in Python

Shulou Source: shulou.com Published: 2022-06-01 19:39:32 10月03日 Update

This article introduces the knowledge about "how to find the integer of the target value in Python". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

Title requirements:

Given an array of integers numbers and a target value target, find the two integers in the array that are the target values and return their array subscripts.

You can assume that there is only one answer for each input. However, you cannot reuse the same elements in this array.

Examples:

Given nums = [2, 7, 11, 15], target = 9

because nums[0] + nums[1] = 2 + 7 = 9

So return [0, 1] problem-solving ideas

Given array arr, initialize dictionary dic, target value target,a,b are elements of array

If there exists such a relation a+b=target, dic[target-a]=a_1 can be obtained if the subscript of a is a_1.

A simple number is a mapping between the index of the current element and the target value minus the value of the current element. If the mapping exists, you can find these two numbers.

code

Python Version

from typing import List

class Solution:

def twoSum(self, nums: List[int], target: int) -> List[int]:

d =dict()

for index,item in enumerate(nums):

if item in d:

return [d[item],index]

else:

d[target-item] = index

#Or

# if target-item in d:

# return [d[target-item],index]

# d[item] = index

if __name__ == "__main__":

l:list = [2,7,11,15,12]

target:int = 19

s = Solution()

print(s.twoSum(l,target))

Go Version

package main

import "fmt"

func solution(nums []int,target int) []int{

m:=make(map[int]int)

for index,value := range nums {

if w,ok:=m[value];ok{

return []int{w,index}

} else{

m[target-value] = index

}

}

return nil

}

func main() {

nums:=[]int{2,7,11,15,12}

fmt.Println("nums",nums)

target:=19

fmt.Println(solution(nums,target))

}"How to find the integer of the target value in Python" is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Tags: Goal target value array integer element subscript two content more knowledge practicality achievement and then code dilemma dictionary reality that is ideas situations Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Technology Shulou Information MariaDB Microsoft