1. 两数之和

1. 两数之和_第1张图片
暴力法,两层for循环,速度慢

// c++
class Solution
 {
    public:vector<int> twoSum(vector<int>& nums, int target) 
    {
        int i, j;
        for(i = 0; i < nums.size() - 1; i++)
          for(j = i + 1; j < nums.size(); j++)
          {
              if (nums[i] + nums[j] == target)
              return {i, j};
          }
          return {};
    }
};
// c#
public class Solution {
    public int[] TwoSum(int[] nums, int target) 
    {
        int[] answer = new int[2];
        int i, j;
        for(i = 0; i < nums.Length - 1; i++)
            for(j = i + 1; j < nums.Length; j++)
                if(nums[i] + nums[j] == target)
                {
                    answer[0] = i; 
                    answer[1] = j;
                    return answer;
                }
        return null;
    }
}

你可能感兴趣的:(1. 两数之和)