【所有详解可以参考】http://tianmaying.com/tutorials/tag/Leetcode?filter=hot&page=1
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解决思路:用一个map,for循环内,遍历数组中的加数1,map用来快速查询要找的加数2,如果找到,就返回map中的这个数,否则如果map没有此数,就put进去,key是数,value是数的index
public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>(); for(int i = 0; i < numbers.length; i++){ Integer diff = (Integer)(target - numbers[i]); if(hash.containsKey(diff)){ int toReturn[] = {hash.get(diff)+1, i+1}; return toReturn; } hash.put(numbers[i], i); } return null; } }
Remove Duplicates from Sorted Array:
Given input array nums = [1,1,2]
,
Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.
thought:
用一个index洗刷掉数组中重复的元素,给数组重新赋值一遍,for循环遍历,当出现重复元素时,continue,否则,将下一个非重复的元素拿到前面来
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length<=1){ return nums.length; } int index = 0; for(int i=0; i<nums.length;i++){ if(nums[index]==nums[i]){ continue; }else{ nums[++index]=nums[i]; } } return index+1; /*Set testSet = new HashSet(); for(int i = 0; i<nums.length ; i++){ testSet.add(new Integer(nums[i])); } return testSet.size();*/ } }