2数之和 (求数组中的下标)

  • 穷举

    1. var twoSum = function (nums, target) {
    2. if (nums.length < 2) {
    3. return [];
    4. }
    5. // 穷举
    6. for (let i = 0; i < nums.length; i++) {
    7. for (let j = i + 1; j < nums.length; j++) {
    8. if (nums[i] + nums[j] === target) {
    9. return [i, j];
    10. }
    11. }
    12. }
    13. };
  • Map

    1. var twoSum = function (nums, target) {
    2. if (nums.length < 2) {
    3. return [];
    4. }
    5. // Map
    6. let diffMap = new Map();
    7. for (let i = 0; i < nums.length; i++) {
    8. if (diffMap.has(target - nums[i])) {
    9. return [i, diffMap.get(target - nums[i])];
    10. } else {
    11. diffMap.set(nums[i], i);
    12. }
    13. }
    14. };

    如果给出的数组是有序的,则可以直接使用双指针 - ”左右夹逼“

  1. var twoSum = function(nums, target){
  2. if(nums.length < 2){
  3. return [];
  4. }
  5. let left = 0, right = nums.length-1;
  6. while(left < right){
  7. let sum = nums[left] + nums[right];
  8. if(sum === target){
  9. return [left, right]
  10. }
  11. if(sum < target){
  12. left++;
  13. }
  14. if(sum > target){
  15. right++;
  16. }
  17. }
  18. }

3数之和(求数组中的元素)

4数之和(求数组中的元素)