[TwoSum]05-04

Algorithmus 2019. 5. 4. 10:56

TwoSum(); // 이중포문 사용

TwoSum2(); //이중포문 사용 안 함

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Algorithm1
{
    public class App
    {
        private int[] arr = { 111927 };
 
        public App()
        {
 
        }
 
        public void Start()
        {
            //a의 각원소를 더해 9가 나오나 검사
            for (int i = 0; i < this.arr.Length; i++)
            {
                Console.WriteLine("index[{0}] : {1}", i, arr[i]);
            }
            Console.WriteLine();
 
            var arr2 = this.TwoSum(this.arr, 9);
            for (int i = 0; i < arr2.Length; i++)
            {
                Console.WriteLine("index : {0}", arr2[i]);
            }
 
            var arr3 = this.TwoSum2(this.arr, 9);
 
            for (int i = 0; i < arr3.Length; i++)
            {
                Console.WriteLine("index : {0}", arr3[i]);
            }
        }
 
        public int[] TwoSum(int[] nums, int target)
        {
            int[] returnArr = new int[2];
            for (int i = 0; i < nums.Length - 1; i++)
            {
                for (int j = 1; j < nums.Length; j++)
                {
                    if (nums[i] + nums[j] == target)
                    {
                        Console.WriteLine("index[{0}], index[{1}] = {2}", i, j, nums[i] + nums[j]);
                        returnArr[0= i;
                        returnArr[1= j;
                    }
                }
            }
            return returnArr;
        }
 
        public int[] TwoSum2(int[] nums, int target)
        {
            int[] returnAtrr = new int[2];
            int index = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                Console.WriteLine("index[{0}] + index[{1}] : {2} ", index, i, nums[index] + nums[i]);
                if (nums[index] + nums[i] == target)
                {
                    returnAtrr[0= index;
                    returnAtrr[1= i;
                    break;
                }
 
                if (returnAtrr[0== 0 && returnAtrr[1== 0 && i == nums.Length-1)
                {
                    index++;
                    i = 0;
                }
            }
 
            return returnAtrr;
        }
    }
}
cs


'Algorithmus' 카테고리의 다른 글

AStar algorithm  (0) 2019.05.20
[Palindrome Number]05-14  (0) 2019.05.14
[TwoSum]05-03  (0) 2019.05.03
<선택정렬 알고리즘>수정1  (0) 2019.03.29
<선택정렬>  (0) 2019.03.29
: