|
| 1 | +package com.algorithm.study.demo.algorithm; |
| 2 | + |
| 3 | +import com.sun.javadoc.SeeTag; |
| 4 | + |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +public class ArrayProject { |
| 8 | + public static void main(String[] args) { |
| 9 | + ArrayProject p=new ArrayProject(); |
| 10 | + |
| 11 | + System.out.println(p.containsDuplicate(new int[]{1,2,3,1})); |
| 12 | + } |
| 13 | + |
| 14 | + /*** |
| 15 | + * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 |
| 16 | + * 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 |
| 17 | + * |
| 18 | + * 示例: |
| 19 | + * 给定 nums = [2, 7, 11, 15], target = 9 |
| 20 | + * 因为 nums[0] + nums[1] = 2 + 7 |
| 21 | + */ |
| 22 | + public int[] twoSum(int[] nums, int target) { |
| 23 | + if (nums.length==0){ |
| 24 | + return new int[]{}; |
| 25 | + } |
| 26 | + Map<Integer,Integer> map=new HashMap(); |
| 27 | + for(int i=0;i<nums.length;i++){ |
| 28 | + int temp=target-nums[i]; |
| 29 | + if(map.containsKey(temp)){ |
| 30 | + return new int[]{map.get(temp),i}; |
| 31 | + } |
| 32 | + map.put(nums[i],i); |
| 33 | + } |
| 34 | + return new int[]{}; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * 给定一个整数数组,判断是否存在重复元素。 |
| 39 | + * 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 |
| 40 | + * 示例 1: |
| 41 | + * 输入: [1,2,3,1] |
| 42 | + * 输出: true |
| 43 | + */ |
| 44 | + public boolean containsDuplicate(int[] nums) { |
| 45 | + if (nums.length==0 || nums.length==1){ |
| 46 | + return true; |
| 47 | + } |
| 48 | + Set<Integer> set=new HashSet<>(); |
| 49 | + for (int i=0;i<nums.length;i++){ |
| 50 | + set.add(nums[i]); |
| 51 | + } |
| 52 | + if (set.size()!=nums.length){ |
| 53 | + return true; |
| 54 | + } |
| 55 | + return false; |
| 56 | + } |
| 57 | +} |
0 commit comments