①:用字典存储(内存消耗大)
public class Solution { public bool ContainsDuplicate(int[] nums) { var dict = new Dictionary<int, int>(); for (int i = 0; i < nums.Length; i++) { if (dict.ContainsKey(nums[i])) { return true; } dict.Add(nums[i], 1); } return false; } }
②:排序(消耗也都挺大的)
public class Solution { public bool ContainsDuplicate(int[] nums) { List<int> list = new List<int>(); list = nums.ToList(); list.Sort(); for (int i = 0; i < list.Count-1; i++) { if (list[i] == list[i + 1]) { return true; } } return false; } }