How to implement the two sum algorithm to find two values in array that add up to target with C#

3 Answers

0 votes
using System;

public class Program
{
	private static int[] twoSum(int[] array, int target) {
		for (int i = 0; i < array.Length; i++) {
			for (int j = i + 1; j < array.Length; j++) {
				if (array[i] + array[j] == target) {
					return new int[] {i, j};
				}
			}
		}
		return new int[] {};
	}
	
	public static void Main(string[] args)
	{
		int[] array = new int[] {1, 5, 7, 6, 4, 3, 2};

		int target = 9;

		int[] indexes = twoSum(array, target);

		if (indexes.Length == 2) {
			Console.WriteLine(indexes[0] + " " + indexes[1]);
		}
		else {
			Console.WriteLine("Not found");
		}
	}
}





/*
run:
   
1 4 
   
*/

 



answered Jul 17, 2023 by avibootz
0 votes
using System;
using System.Collections.Generic;

public class Program
{
	private static int[] twoSum(int[] array, int target) {
		IDictionary<int, int> hmap = new Dictionary<int, int>();

		for (int i = 0; i < array.Length; i++) {
			int complement = target - array[i];
			if (hmap.ContainsKey(complement)) {
				return new int[] {hmap[complement], i};
			}
			else {
				hmap[array[i]] = i;
			}
		}

		return new int[] {};
	}
	
	public static void Main(string[] args)
	{
		int[] array = new int[] {1, 5, 7, 6, 4, 3, 2};

		int target = 9;

		int[] indexes = twoSum(array, target);

		if (indexes.Length == 2) {
			Console.WriteLine(indexes[0] + " " + indexes[1]);
		}
		else {
			Console.WriteLine("Not found");
		}
	}
}





/*
run:
   
1 4 
   
*/




 



answered Jul 17, 2023 by avibootz
0 votes
using System;

public class Program
{
	private static int[] twoSum(int[] array, int target) {
		Array.Sort(array);
		int left = 0, right = array.Length - 1;

		while (left < right) {
			if (array[left] + array[right] == target) {
				return new int[] {array[right], array[left]};
			}
			else if (array[right] + array[left] < target) {
				left++;
			}
			else {
				right--;
			}
		}

		return new int[] {};
	}
	
	public static void Main(string[] args)
	{
		int[] array = new int[] {1, 5, 7, 6, 4, 38, 23};

		int target = 9;

		int[] values = twoSum(array, target);

		if (values.Length == 2) {
			Console.WriteLine(values[0] + " " + values[1]);
		}
		else {
			Console.WriteLine("Not found");
		}
	}
}




/*
run:
   
5 4
   
*/







 



answered Jul 17, 2023 by avibootz
...