前端算法:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数、判断一个整数是否是回文数

淡淡的烟草味﹌ 2022-05-12 17:14 254阅读 0赞
  1. <!--
  2. 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
  3. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
  4. 示例:
  5. 给定 nums = [2, 7, 11, 15], target = 9
  6. 因为 nums[0] + nums[1] = 2 + 7 = 9
  7. 所以返回 [0, 1]
  8. @link https://leetcode-cn.com/problems/two-sum/solution/
  9. -->
  10. <script>
  11. function twoSum(nums, target) {
  12. const hash = {};
  13. for (let i = 0; i < nums.length; i++) {
  14. if (hash[nums[i]] !== undefined) {
  15. return [hash[nums[i]], i];
  16. } else {
  17. let newKey = target - nums[i]
  18. hash[newKey] = i;
  19. }
  20. }
  21. return [-1,-1]
  22. }
  23. let nums = [2, 7, 11, 15], target = 17;
  24. console.log(twoSum(nums,target));
  25. </script>
  26. <!--
  27. 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
  28. 输入: 121
  29. 输出: true
  30. @link: https://leetcode-cn.com/problems/palindrome-number/solution/
  31. -->
  32. <script>
  33. function IsPalindrome(x){
  34. // 特殊情况:
  35. // 如上所述,当 x < 0 时,x 不是回文数。
  36. // 同样地,如果数字的最后一位是 0,为了使该数字为回文,
  37. // 则其第一位数字也应该是 0
  38. // 只有 0 满足这一属性
  39. if(x < 0 || (x % 10 == 0 && x != 0)) {
  40. return false;
  41. }
  42. let rev = 0; // reversed number
  43. while (x >= 10) {
  44. let cur = x % 10;
  45. rev = rev*10 + cur;
  46. if (x === rev) return true; // check before changing
  47. x = ~~(x / 10); // better replace for Math.floor(), bit operator '~' inverts all the bits in your number and in the process converts the number to an int
  48. if (x === rev) return true; // check after changing
  49. if (x < rev) return false; // stop in case reversed number becomes greater than original value
  50. }
  51. return false; // the longest case (diff in the middle) // [77778777, 10004001]
  52. }
  53. console.log(IsPalindrome(69699696))
  54. </script>

发表评论

表情:
评论列表 (有 0 条评论,254人围观)

还没有评论,来说两句吧...

相关阅读