LeetCode 1. Two Sum

Two Sum.

My solution is brute-force. But there are linear solutions using either hash table or a two-end merged technique.

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        bool done=false;
        int[] ret = new int[2];
        for (int i=0; i < nums.Length-1; i++) {
            for(int j=i+1; j < nums.Length; j++){
                if(nums[i]+nums[j] == target){
                    ret[0] = i;
                    ret[1] = j;
                    done = true;
                    break;
                }
            }
            if (done == true) break;
        }
        return ret;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *