算法题

https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

  1. var getIntersectionNode = function(headA, headB) {
  2. if (!headA || !headB) return null;
  3. var head1 = headA;
  4. var head2 = headB;
  5. while(head1 !== head2) {
  6. head1 = !head1 ? headB : head1.next;
  7. head2 = !head2 ? headA : head2.next;
  8. }
  9. return head1
  10. };

解法:
双指针

手写题

写一个拖拽组件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. body {
  10. position: relative;
  11. margin: 0;
  12. padding: 0
  13. }
  14. #box {
  15. position: absolute;
  16. width: 120px;
  17. height: 120px;
  18. background-color: red;
  19. }
  20. </style>
  21. </head>
  22. <body>
  23. <div id="box"></div>
  24. <script>
  25. window.onload = function () {
  26. // drag处于绝对定位状态
  27. let drag = document.getElementById("box");
  28. drag.onmousedown = function (e) {
  29. var e = e || window.event;
  30. // 鼠标与拖拽元素边界的距离 = 鼠标与可视区边界的距离 - 拖拽元素与边界的距离
  31. let diffX = e.clientX - drag.offsetLeft;
  32. let diffY = e.clientY - drag.offsetTop;
  33. drag.onmousemove = function (e) {
  34. // 拖拽元素移动的距离 = 鼠标与可视区边界的距离 - 鼠标与拖拽元素边界的距离
  35. let left = e.clientX - diffX;
  36. let top = e.clientY - diffY;
  37. // 避免拖拽出可视区
  38. if (left < 0) {
  39. left = 0;
  40. } else if (left > window.innerWidth - drag.offsetWidth) {
  41. left = window.innerWidth - drag.offsetWidth;
  42. }
  43. if (top < 0) {
  44. top = 0;
  45. } else if (top > window.innerHeight - drag.offsetHeight) {
  46. top = window.innerHeight - drag.offsetHeight;
  47. }
  48. drag.style.left = left + "px";
  49. drag.style.top = top + "px";
  50. };
  51. drag.onmouseup = function (e) {
  52. this.onmousemove = null;
  53. this.onmouseup = null;
  54. };
  55. };
  56. };
  57. </script>
  58. </body>
  59. </html>

注意边界处理