SyntaxHighlighter

2021-10-03

LeetCode 01: Two Sum

 長い間ウワサは聞いておりますが、初めて触りました。リートコード(LeetCode)という中国発のネットジャージシステム。一応自分が登録したのはアメリカサーバですけどね。

多分アルゴリズム上ではそこまで最適化していませんが、一応コードを記録しておくことに:


public class Solution {
    public int[] TwoSum(int[] nums, int target) {
            int index1=0;
            int index2=1;

            int maxindex = nums.Length;

            while (true)
            {
                int solution = nums[index1] + nums[index2];
                if (solution == target)
                {
                    int[] result = new int[] { index1, index2 };
                    return result;
                }

                index2++;

                if(index2 >= maxindex)
                {
                    index1++;
                    index2 = index1 + 1;
                }
            }
    }
}
            

人気の投稿