Skip to content

Latest commit

 

History

History
76 lines (54 loc) · 2.57 KB

File metadata and controls

76 lines (54 loc) · 2.57 KB

English Version

题目描述

给定一个对象 obj,返回一个反转的对象 invertedObj

invertedObj 应该以 obj 的键作为值,以 obj 的值作为键。题目保证 obj 中的值仅为字符串。该函数应该处理重复值,也就是说,如果在 obj 中有多个具有相同值的键,那么 invertedObj 应该将该值映射到一个包含所有相应键的数组中。

 

示例 1:

输入:obj = {"a": "1", "b": "2", "c": "3", "d": "4"}
输出:invertedObj = {"1": "a", "2": "b", "3": "c", "4": "d"}
解释:The keys from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.

示例 2:

输入:obj = {"a": "1", "b": "2", "c": "2", "d": "4"}
输出:invertedObj = {"1": "a", "2": ["b", "c"], "4": "d"}
解释:There are two keys in obj with the same value, the invertedObj mapped the value to an array containing all corresponding keys.

示例 3:

输入:obj = ["1", "2", "3", "4"]
输出:invertedObj = {"1": "0", "2": "1", "3": "2", "4": "3"}
解释:Arrays are also objects therefore array has changed to an object and the keys (indices) from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.

 

提示:

  • obj 是一个有效的 JSON 对象
  • typeof obj[key] === "string"
  • 2 <= JSON.stringify(obj).length <= 10**5

解法

TypeScript

function invertObject(obj: Record<any, any>): Record<any, any> {
    const ans: Record<any, any> = {};
    for (const key in obj) {
        if (ans.hasOwnProperty(obj[key])) {
            if (Array.isArray(ans[obj[key]])) {
                ans[obj[key]].push(key);
            } else {
                ans[obj[key]] = [ans[obj[key]], key];
            }
        } else {
            ans[obj[key]] = key;
        }
    }
    return ans;
}