每日两题 T23

时间:2022-07-22
本文章向大家介绍每日两题 T23,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

算法

LeetCode T355. 设计推特[1]

描述

设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近十条推文。你的设计需要支持以下的几个功能:

1.postTweet(userId, tweetId): 创建一条新的推文2.getNewsFeed(userId): 检索最近的十条推文。每个推文都必须是由此用户关注的人或者是用户自己发出的。推文必须按照时间顺序由最近的开始排序。3.follow(followerId, followeeId): 关注一个用户4.unfollow(followerId, followeeId): 取消关注一个用户

示例

Twitter twitter = new Twitter();

// 用户1发送了一条新推文 (用户id = 1, 推文id = 5).
twitter.postTweet(1, 5);

// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
twitter.getNewsFeed(1);

// 用户1关注了用户2.
twitter.follow(1, 2);

// 用户2发送了一个新推文 (推文id = 6).
twitter.postTweet(2, 6);

// 用户1的获取推文应当返回一个列表,其中包含两个推文,id分别为 -> [6, 5].
// 推文id6应当在推文id5之前,因为它是在5之后发送的.
twitter.getNewsFeed(1);

// 用户1取消关注了用户2.
twitter.unfollow(1, 2);

// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
// 因为用户1已经不再关注用户2.
twitter.getNewsFeed(1);

代码

/**
 * Initialize your data structure here.
 */
var Twitter = function() {
  this.time = 0;
  this.users = {}; // follows
};

/**
 * Compose a new tweet. 
 * @param {number} userId 
 * @param {number} tweetId
 * @return {void}
 */
Twitter.prototype.postTweet = function(userId, tweetId) {
  this.time += 1;
  let { users} = this;
  if (users[ userId ] === undefined) users[ userId ] = [];
  if (users[ userId ][ 'tweets' ] === undefined) users[ userId ][ 'tweets' ] = [];
  // 考虑重复推文
  let hasTweets = [];
  for (let tweet of users[ userId ][ 'tweets' ]) {
    hasTweets.push( tweet.tweetId );
  }
  if (hasTweets.includes(tweetId)) return;
  users[ userId ][ 'tweets' ].push({ tweetId, time: this.time });
};

/**
 * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. 
 * @param {number} userId
 * @return {number[]}
 */
Twitter.prototype.getNewsFeed = function(userId) {
  let users = this.users,
      list = [],
      ids = [userId]; // 自己和自己关注的 userId
  if (users[ userId ] === undefined) return [];
  let follows = users[ userId ][ 'follows' ];
  if (follows !== undefined) {
    ids.push( ...follows );
  }

  for (let userid of ids) {
    if (users[ userid ] === undefined) continue;
    if (users[ userid ][ 'tweets' ] === undefined) continue;
    list.push( ...users[ userid ][ 'tweets' ] )
  }

  list.sort( (a, b) => b.time - a.time );

  let res = new Set(); // 去重重复推文,防止自己关注自己的情况
  for (let i = 0; i < list.length; i++) {
    res.add( list[i]['tweetId'] );
    if (res.size === 10) break;
  }
  return [...res];
};

/**
 * Follower follows a followee. If the operation is invalid, it should be a no-op. 
 * @param {number} followerId 
 * @param {number} followeeId
 * @return {void}
 */
Twitter.prototype.follow = function(followerId, followeeId) {
  let users = this.users;
  if (users[ followerId ] === undefined) users[ followerId ] = [];
  if (users[ followerId ][ 'follows' ] === undefined) {
    users[ followerId ][ 'follows' ] = [];
  }
  if (users[ followerId ]['follows'].indexOf( followeeId ) !== -1) return ;
  users[ followerId ]['follows'].push( followeeId );
};

/**
 * Follower unfollows a followee. If the operation is invalid, it should be a no-op. 
 * @param {number} followerId 
 * @param {number} followeeId
 * @return {void}
 */
Twitter.prototype.unfollow = function(followerId, followeeId) {
  let users = this.users;
  if (users[ followerId ] === undefined) return ;
  if (users[ followerId ][ 'follows' ] === undefined) return ;
  let userFollows = users[ followerId ][ 'follows' ];
  let index = userFollows.indexOf( followeeId );
  if (index === -1) return ;
  userFollows.splice(index, 1);
};

/**
 * Your Twitter object will be instantiated and called as such:
 * var obj = new Twitter()
 * obj.postTweet(userId,tweetId)
 * var param_2 = obj.getNewsFeed(userId)
 * obj.follow(followerId,followeeId)
 * obj.unfollow(followerId,followeeId)
 */

前端

React Portal 有哪些使用场景

Portal 提供了一种将子节点渲染到存在于父组件以外的 DOM 节点的优秀的方案。比如,在某个场景下,父组件的 overflow: hiddenz-index 属性被设置时,会影响子元素,假如我们不希望这样,这是我们就可以选用 Portal,让子元素跳出父元素的圈圈。常用的场景有:Modal 模态框Popover 弹出 Drawer抽屉 等。

这样一来,我们现在组件的结构可以像这样:

<html>
  <body>
    <div id="app"></div>
    <div id="modal"></div>
    <div id="gotop"></div>
    <div id="alert"></div>
  </body>
</html>

编写组件代码,保证模态框被单例挂载到 id=modal 的节点上

const modalRoot = document.getElementById('modal');

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement('div');
  }

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }

  render() {
    return ReactDOM.createPortal(
      this.props.children,
      this.el,
    );
  }
}

如此一来,Modal 组件的挂载节点就不用跟随父节点了,Portal 允许我们根据需求任意地挂载节点。

References

[1] 355. 设计推特: https://leetcode-cn.com/problems/design-twitter/