[알고리즘 연습 leetcode 편의 더 블 포인터 (167, 344, 345)

2154 단어
[167] Two Sum II - Input array is sorted
/*
 * @lc app=leetcode id=167 lang=javascript
 *
 * [167] Two Sum II - Input array is sorted
 */
/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 *      
 *      target,right      
 *      target,left      
 *      O(n)
 */
var twoSum = function(numbers, target) {
  let left = 0;
  let right = numbers.length - 1;

  while (left < right) {
    const sum = numbers[left] + numbers[right];
    if (sum === target) {
      return [left + 1, right + 1];
    }
    if (sum > target) {
      right--;
    }
    if (sum < target) {
      left++;
    }
  }
};
console.log(twoSum([2, 7, 11, 15], 9));

[344] Reverse String
/*
 * @lc app=leetcode id=344 lang=javascript
 *
 * [344] Reverse String
 */
/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
  let left = 0;
  let right = s.length - 1;
  while (left < right) {
    if (s[left] !== s[right]) {
      [s[left], s[right]] = [s[right], s[left]];
    }
    left++;
    right--;
  }
  return s;
};
console.log(reverseString(['h', 'e', 'l', 'l', '0']));

[345] Reverse Vowels of a String
/*
 * @lc app=leetcode id=345 lang=javascript
 *
 * [345] Reverse Vowels of a String
 */
/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
  let str = s.split('');
  let left = 0;
  let right = str.length - 1;
  const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
  while (left < right) {
    if (vowels.indexOf(str[left]) === -1) {
      left++;
    }
    if (vowels.indexOf(str[right]) === -1) {
      right--;
    }
    if (vowels.indexOf(str[left]) !== -1 && vowels.indexOf(str[right]) !== -1) {
      [str[left], str[right]] = [str[right], str[left]];
      left++;
      right--;
    }
  }
  return str.join('');
};
console.log(reverseVowels('leetcode'));

좋은 웹페이지 즐겨찾기