Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Recommended reading

  • CSDN home page
  • GitHub open source address
  • Unity3D plugin sharing
  • Jane’s address book
  • My personal blog
  • QQ group: 1040082875

Hello, everyone, I am a little Magic dragon, Unity3D software engineer, VR, AR, virtual simulation direction, update software development skills from time to time, life perception, remember to use one button three links.

A, the title

1. Algorithm topic

“Find two integers in the array and the array subscript for the target value.”

Title link: Source: LeetCode

Link: leetcode-cn.com/problems/tw…

2

Given an integer array nums and an integer target value target, find the two integers in the array and the target value target and return their array subscripts.

You can assume that there is only one answer for each type of input. However, the same element in the array cannot be repeated in the answer.

You can return the answers in any order.

Such as:

Nums = [1,2,3,4,5,6,7],target=4 output: [0,2] because nums[0] + nums[2] =4, return [0,2]

Second, the problem solving

1. Analysis of ideas

It’s easy to think of iterating through each number x in the array and looking for target-x in the array. Therefore, you can use a two-level loop where the two numbers are added and the output value is the array subscript of target.

2. Code implementation

public class Solution 
{
    public int[] TwoSum(int[] nums, int target) 
    {
        int n = nums.Length;
        for (int i =0; i < n ; i++) {for(int j = i + 1; j<n ; j++) {if (nums[i]+nums[j] == target)
                {
                    return new int[]{i,j}; }}}return new int[0]; }}Copy the code

Execution Result:

3. Time complexity

Time complexity: O(N^2)

N is the number of elements in the array, and the worst case is that any two elements in the array have to be matched once, so the time complexity is high.

Third, summary

This is the first time in the buckle learning algorithm, although solved, but the time complexity is relatively high, or not perfect.

See there is a great use of hash mapping can greatly improve the efficiency of the algorithm, this will learn about optimization later.

Ah, set a flag. Ha ha