classSolution{ publicint[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == target - nums[j]) { returnnewint[]{i, j}; }
} }
thrownew IllegalArgumentException("No two sum solution !!!");
} }
第二种:代码实现高级版,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution{ publicstaticint[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { returnnewint[]{map.get(complement), i}; } map.put(nums[i], i); } thrownew IllegalArgumentException("No two sum solution !!!");
} }
移除元素
题目描述
代码实现
1 2 3 4 5 6 7 8 9 10 11 12
classSolution{ publicintremoveElement(int[] nums, int val){ int count = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] != val){ nums[count++] = nums[i]; } }