《2018年2月19日》【连续131天】
标题:core java5.3;
内容:
A.补充:
a.重定义equals时,就必须重定义HashCode方法;
B.登了一下LeetCode,顺便看了第一道题,题目都是英文,看了给的格式才知道是要写个函数:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result =new int[2];
Top:
for(int i=0;i<nums.length;++i)
for(int j=i+1;j<nums.length;++j)
{
if(nums[i]+nums[j]==target)
{
result[0]=i;
result[1]=j;
break Top;
}
}
return result;
}
}
这是直接解的,复杂度为O(n^2),阅读了别人的解法后,发现可以使用HashMap简化:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result =new int[2];
HashMap<Integer,Integer> map =new HashMap<>();
for(int i=0;i<nums.length;i++)
map.put(nums[i],i);
for(int i=0;i<nums.length;i++)
{
int b =target-nums[i];
if(map.containsKey(b))
if(map.get(b) != i)
{
result[0] =map.get(b);
result[1] =i;
break;
}
}
return result;
}
}
int[] result =new int[2];
HashMap<Integer,Integer> map =new HashMap<>();
for(int i=0;i<nums.length;i++)
map.put(nums[i],i);
for(int i=0;i<nums.length;i++)
{
int b =target-nums[i];
if(map.containsKey(b))
if(map.get(b) != i)
{
result[0] =map.get(b);
result[1] =i;
break;
}
}
return result;
}
}
C.
1.ArrayList:
可以通过ensureCapacity分配预定的空间,这样在一定范围内,add就不会一直创建新的内存空间;
当ArrayList内部确定时,使用trimToSize将会使多余的内存空间被回收;
使用get,add,ToArray等方法;