samedi 22 mai 2021

Given an array of integers, return indices of the two numbers with for loops and if statements

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

I understand this question has been asked many different ways. I understand I am supposed to use a hash map. But still... can this work? and why am i getting a doesn't always return value error?

'using System.Linq;


public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        int arrayLength = nums.Count();
        var a = 0;
        var b = 0;
        for (int i = 0; i <= arrayLength; i++) {
            if (i == arrayLength) {
                a += 1;
                i = 0;
            }
            if (nums[a] + nums[i] == target) {
                int[] answer = {a, i};
                return answer;
            }
        }
    }
}'

Aucun commentaire:

Enregistrer un commentaire