奇数个异或是本身,偶数个是0;0^a=a;异或有交换律。
1.给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
class Solution {
public int singleNumber(int[] nums) {
int m = nums[0];
for(int i = 1; i<nums.length; i++){
m = m^nums[i];
}
return m;
}
}
2.给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
class Solution {
public void rotate(int[] nums, int k) {
int m = nums.length;
int[] arr = new int[m];
for(int i = 0; i<m; i++){
arr[(i+k)%m] = nums[i];
}
System.arraycopy(arr,0,nums,0,m);
}
}
3.给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
你可以按任意顺序返回答案。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i<nums.length; i++){
if(hash.containsKey(target-nums[i])){
int[] arr = {i,hash.get(target-nums[i])};
return arr;
}
hash.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}