'Algorithm/푼 문제'에 해당되는 글 1건

  1. 2019.05.03 1. Two Sum

1. Two Sum

Algorithm/푼 문제 2019. 5. 3. 10:43

2중 for문 이용해서 푼 것


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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Q01
{
    public class Solution
    {
        private int target;
 
        public Solution()
        {
            Console.Write("찾으실 숫자를 입력하세요 : ");
            var input = Console.ReadLine();
            Int32.TryParse(input, out this.target);
            var twoNums = this.TwoSum(new int[] { 13567 }, this.target);
            Console.WriteLine("{0}, {1}", twoNums[0], twoNums[1]);
        }
 
        public int[] TwoSum(int[] nums, int target)
        {
            int[] result = null;
 
            for (int idx = 0; idx < nums.Length; idx++)
            {
                for (int searchIdx = idx + 1; searchIdx < nums.Length; searchIdx++)
                {
                    if ((nums[searchIdx] + nums[idx]) == target)
                    {
                        result = new int[] { nums[idx], nums[searchIdx] };
                        return result;
                    }
                }
            }
            return null;
        }
    }
}
 
cs


2중 for문 이용하지 않고 푼 것


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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Q01
{
    public class Solution
    {
        private int target;
 
        public Solution()
        {
            Console.Write("찾으실 숫자를 입력하세요 : ");
            var input = Console.ReadLine();
            Int32.TryParse(input, out this.target);
            var twoNums = this.TwoSum(new int[] { 13567 }, this.target);
            Console.WriteLine("{0}, {1}", twoNums[0], twoNums[1]);
        }
 
        public int[] TwoSum(int[] nums, int target)
        {
            int[] result;
            var idx = 0;
            var cnt = idx + 1;
            while(true)
            {
                if(cnt == nums.Length)
                {
                    idx++;
                    cnt = idx + 1;
                    if(idx == nums.Length)
                    {
                        break;
                    }
                }
                if((nums[idx] + nums[cnt]) == target)
                {
                    result = new int[] { nums[idx], nums[cnt] };
                    return result;
                }
                cnt++;
            }
            return null;
        }
    }
}
 
cs


: