一、求平面点集中,离所有点距离和最小的点坐标和距离值。
问题的关键是:
1、距离定义
2、找出某个新的点坐标,离所有已知点距离和最近
3、用计算机实现。
此问题类似于机器学习中的回归问题。
当我们用一条直线拟合离散点时,也会用距离和最小评价拟合的程度的好。
而回归中使用是梯度下降法,所以这个也可以用梯度下降法,语言最好用python,这样就能用已知的库和函数求解了。
二、找一个未排序数组中确实的正整数。
2.Givenan unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
java源码如下:
package test;
public class MissingInteger {
static int missing(int[] array) {
int ret = -1;
boolean sorted = false;
int startIndex = -1;
int endIndex = -1;
for (int i = 1; i < array.length; i++) {
if ( !sorted ) {
if (array[i - 1] + 1 == array[i]) {
sorted = true;
startIndex = i - 1;
}
} else {
if (array[i - 1] + 1 != array[i]) {
endIndex = i - 1;
}
}
}
if (startIndex == 0 && array[startIndex] <= 1) {
ret = array[endIndex] + 1;
} else {
ret = array[startIndex] - 1;
}
return ret;
}
public static void main(String[] args) {
// int[] array = {3,4,-1,1};
int[] array = {1,2,0};
int missing = missing(array);
System.out.println("the missing integer is: " + missing);
}
}
测试结果为:
3
三、找出最长回文字符串
回文字符串,即是左右对称的字符串。形式如abcba、adffda。有奇数和偶数形式的回文。
如何在一个字符串数组中找出长度最大的回文字符串呢?
java源码如下:
package test;
public class LongestPalindrome {
static String findLongestPalindrome(String in) {
char[] input = in.toCharArray();
int longestPalindromeStart = 0;
int longestPalindromeEnd = 0;
for (int mid = 0; mid < input.length; mid++) {
// for odd palindrom case like 12321, 3 will be the mid
int left = mid - 1;
int right = mid + 1;
// we need to move in the left and right side by 1 place till they
// reach the end
while (left >= 0 && right < input.length) {
// below check to find out if its a palindrome
if (input[left] == input[right]) {
// update global indexes only if this is the longest one
// till now
if (right - left > longestPalindromeEnd - longestPalindromeStart) {
longestPalindromeStart = left;
longestPalindromeEnd = right;
}
}
left--;
right++;
}
// for even palindrome, we need to have similar logic with mid size
// 2
// for that we will start right from one extra place
left = mid - 1;
right = mid + 2;// for example 12333321 when we choose 33 as mid
while (left >= 0 && right < input.length) {
if (input[left] == input[right]) {
if (right - left > longestPalindromeEnd - longestPalindromeStart) {
longestPalindromeStart = left;
longestPalindromeEnd = right;
}
}
left--;
right++;
}
}
// we have the start and end indexes for longest palindrome now
return in.substring(longestPalindromeStart, longestPalindromeEnd + 1);
}
public static void main(String[] args) {
String text = "abcbasd"; //even
String longestPalindrome = findLongestPalindrome(text);
System.out.println(longestPalindrome);
}
}
运行结果如下:
abcba
注意:此程序可以判断字符串,而不管字符串里的内容是数字还是字母。
回文可能有奇数和偶数区别,注意区分。