【LeetCode】解析_1. Two Sum

1. Two Sum(Easy)

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

問題及參考網站取自 Leetcode.

我的解答

雙迴圈 (這是比較爛的方法)

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        for(int i = 0; i < nums.Length; i++){
            // j=j+1是因為 同個數字沒辦法重複加總; 
            for(int j = i + 1 ; j < nums.Length; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i, j};
                }
            }
        }
        // 因為有可能都沒辦法總和到target;
        throw new Exception("error");
    }
}