版权声明:本文为博主原创文章,转载请标注原文档地址。 https://blog.csdn.net/jin343229836/article/details/70140903
1、一个数组nums,输入target,计算nums中哪两个索引下的值的和等于target,并输出两个的索引值
public int[] 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)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
2、计算两个数的汉明距离,汉明距离为两个数的二进制相比较,有几位不同
public class Solution {
public static void main(String[] args) {
System.out.println(hammingDistance(4,1));
}
public static int hammingDistance(int x, int y) {
int z = x^y;
int num = 0;
while(z!=0){
if(z%2==1){
num++;
}
z/=2;
}
return num;
}
}
3、计算补码对应的32位二进制
public static int findComplement(int num) {
return ~num & ((Integer.highestOneBit(num) << 1) - 1);
}
4、Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
给定一个数组,长度为2n,把他们分成n组,使min(ai,bi)和相加尽可能的大
Example 1:
Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4.
Note:
- n is a positive integer, which is in the range of [1, 10000].
- All the integers in the array will be in the range of [-10000, 10000]
思路:先进行排序,在取相邻的两个数取最小值进行想加
public class Solution {
public static void main(String[] args){
int[] nums = {1,4,3,2,5,6};
int i = arrayPairSum(nums);
System.out.print(i);
}
public static int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int sum = 0;
for(int i=0;i<nums.length;i+=2){
if(nums[i]<nums[i+1]){
sum = sum + nums[i];
}else{
sum = sum + nums[i+1];
}
}
return sum;
}
}
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
Subscribe to see which companies asked this question.
public class Solution {
public static void main(String[] args) {
System.out.print(reverseWords("Let's take LeetCode contest"));
}
public static String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
String[] str = s.split(" ");
for(int i=0;i<str.length;i++){
StringBuilder strs = new StringBuilder();
strs.append(str[i]);
strs.reverse();
if(i==str.length-1){
sb.append(strs);
}else{
sb.append(strs+" ");
}
}
return sb.toString();
}
}