力扣刷题日记-599-两个列表的最小索引总和

84 阅读1分钟
  • 假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。

你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设答案总是存在。

来源:力扣(LeetCode) 链接:leetcode.cn/problems/mi… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
 * @param {string[]} list1
 * @param {string[]} list2
 * @return {string[]}
 */
var findRestaurant = function(list1, list2) {
    let list1Len = list1.length, list2Len = list2.length
    let common = []
    if(list1Len <= list2Len) {
        for(let i = 0; i < list1Len; i++){
            let idx = list2.indexOf(list1[i])
            if(idx > -1){
                common.push({name: list1[i], idx: idx + i})
            }
        }
    }else {
        for(let i = 0; i < list2Len; i++) {
            let idx = list1.indexOf(list2[i])
            if(idx > -1){
                common.push({name: list2[i], idx: idx + i})
            }
        }
    }
    common.sort((a,b) => a.idx - b.idx)
    let result = []
    for(let i = 0; i < common.length; i++) {
        if(common[0].idx == common[i].idx) {
            result.push(common[i].name)
        }
    }
    return result
};