gpt4 book ai didi

java - 日期数组中最长的连续子序列

转载 作者:行者123 更新时间:2023-12-01 07:49:27 24 4
gpt4 key购买 nike

嗨,我有一个Arraylist,其中包含按升序排列的日期。日期的格式为 yyyy-MM-dd。现在我想找出该 Arraylist 中最长的连续子序列。我已经在线检查了解决方案,但它们与 int 数组相关,我想找出日期数组。int 数组的代码:

// Returns length of the longest contiguous subarray
int findLength(int arr[], int n)
{
int max_len = 1; // Initialize result
for (int i=0; i<n-1; i++)
{
// Initialize min and max for all subarrays starting with i
int mn = arr[i], mx = arr[i];

// Consider all subarrays starting with i and ending with j
for (int j=i+1; j<n; j++)
{
// Update min and max in this subarray if needed
mn = min(mn, arr[j]);
mx = max(mx, arr[j]);

// If current subarray has all contiguous elements
if ((mx - mn) == j-i)
max_len = max(max_len, mx-mn+1);
}
}
return max_len; // Return result
}

// Utility functions to find minimum and maximum of
// two elements
int min(int x, int y) { return (x < y)? x : y; }
int max(int x, int y) { return (x > y)? x : y; }

最佳答案

tl;博士

ChronoUnit.DAYS.between ( 
LocalDate.parse( previousString ) ,
LocalDate.parse( currentString )
)

字符串!=日期

I have an Arraylist containing dates in increasing order. Dates are of this format yyyy-MM-dd.

这意味着您有 List String 对象,而不是日期。这里的主要挑战是获取日期对象,以便您可以计算它们之间的天数。

java.time

现代方法是使用 java.time 类来取代麻烦的旧遗留类(DateCalendar 等)。

您的输入字符串恰好符合标准ISO 8601格式。还有java.time类在解析/生成字符串时默认使用 ISO 8601 格式。所以不需要指定formatting pattern .

List<String> inputs = new ArrayList<> ();
inputs.add ( "2016-01-23" );
inputs.add ( "2016-01-25" );
inputs.add ( "2016-02-22" ); // End of longest period between dates.
inputs.add ( "2016-02-25" );
inputs.add ( "2016-02-28" );

LocalDate类表示仅日期值,没有时间和时区。

此示例代码的策略是计算每个 LocalDate(从每个传入字符串解析)与前一个 LocalDate 之间的天数。如果比迄今为止看到的最长的数据长,则忘记旧的最长数据并记住当前循环的数据。

LocalDate longestStart = null;
LocalDate longestStop = null;
LocalDate previousDate = null;
long longestInDays = 0;

ChronoUnit enum有方便的方法,例如计算经过的天数。

for ( String input : inputs ) {
LocalDate currentDate = LocalDate.parse ( input );
if ( null == previousDate ) { // First loop.
previousDate = currentDate;
continue; // Skip the rest of this first loop.
}
long currentDays = ChronoUnit.DAYS.between ( previousDate , currentDate );
if ( currentDays > longestInDays ) {
// If the current loop exceeds previous longest, remember this one as longest.
longestInDays = currentDays;
longestStart = previousDate;
longestStop = currentDate;
}
// Prepare for next loop.
previousDate = currentDate;
}

将结果转储到控制台。

System.out.println ( "Longest period has days: " + longestInDays + " = " + longestStart + "/" + longestStop );

Longest period has days: 28 = 2016-01-25/2016-02-22

参见live code in IdeOne.com .

关于java - 日期数组中最长的连续子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41170865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com