给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。java
你能够假设每种输入只会对应一个答案。可是,数组中同一个元素不能使用两遍。数组
示例:函数
给定 nums = [2, 7, 11, 15], target = 9指针
由于 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]code
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/two-sum排序
利用双层for循环,定义两个指针i,j;索引
看第i个数与第i个数之后的数相加是否为target目标值,若相等则返回i,j的索引位置;不然i++。leetcode
class Solution { public int[] twoSum(int[] nums, int target) { for (int i=0;i<nums.length-1;i++){ for (int j = i+1; j < nums.length ; j++) { if((nums[i] + nums[j]) == target){ return new int[]{i,j}; } } } throw new IllegalArgumentException("no two sum solution"); } }
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); // 将数组中的值和数组下标对应存入map集合中 for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int j = 0; j < nums.length; j++) { int comp = target - nums[j]; if (map.containsKey(comp)&&map.get(comp)!=j) { return new int[]{j,map.get(comp)}; } } throw new IllegalArgumentException("No two sum solution"); } }
ps: 采用Map集合实现将索引和数组中的数据进行一一对应,采用单重for循环将时间复杂度从O(n^2)降至O(n);利用containsKey判断是否存在所求值,利用get排除索引号相同的状况。rem
给定一个排序数组,你须要在 原地 删除重复出现的元素,使得每一个元素只出现一次,返回移除后数组的新长度。get
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 而且原数组 nums 的前两个元素被修改成 1, 2。
你不须要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 而且原数组 nums 的前五个元素被修改成 0, 1, 2, 3, 4。
你不须要考虑数组中超出新长度后面的元素。
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
利用快慢指针。
假若慢指针指向的值与快指针的值不相同,则慢指针+1;将快指针的值赋给慢指针所在位置。
最后返回慢指针数+1便可
class Solution { public int removeDuplicates(int[] nums) { // 若是数组为空 if (nums.length == 0){ return 0; } // 定义快慢指针,i为慢指针,为快指针 int i=0,j=1; for (;j < nums.length; j++) { if(nums[j] != nums[i]){ i++; nums[i] = nums[j]; } } return i+1; } }