您的位置:首页 > 大数据 > 人工智能

Leetcode_217_Contains Duplicate

2015-05-30 09:16 393 查看
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/46271159

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

思路:

(1)题意为判断给定的整数数组中是否包含相同的元素,如果包含则返回false,否则返回true。

(2)该题比较简单。通过构造一个Map来存放遍历得到的数值,如果在后续的遍历中从Map能够获取到value,则说明有重复的,返回false;否则继续遍历直到结束,返回true。

(3)详情见下方代码。希望对你有所帮助。

算法代码实现如下:

/**
* @author liqqc
*/
import java.util.HashMap;
import java.util.Map;

public class ContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
if (nums == null || nums.length == 0) {
return false;
}

Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (maps.get(nums[i]) == null) {
maps.put(nums[i], nums[i]);
} else if (maps.get(nums[i]) != null) {
return true;
}
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: